utilização de mysqli_prepare previne os principais ataques de sql injection

Question: Eu sei que afunção mysqli_prepare é utilizada para preparar as consultas SQL e protegê-las contra SQL Injection.
Encontrei duas páginas sobre SQL Injection:

https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet
https://www.netsparker.com/blog/web-security/sql-injection-cheat-sheet/

Estou começando a estudar sobre o assunto, e queria saber se a função mysqli_prepare consegue prevenir esses casos, ou se precisaria de "algo mais" no meu script PHP além da mysqli_prepare.
A minha dúvida é:
A utilização de mysqli_prepare previne TODOS os ataques de SQL Injection, ou é restrita aos principais tipos de ataques de SQL Injection ?
Comment: Possível duplicidade http://pt.stackoverflow.com/questions/3864/como-prevenir-inje%C3%A7%C3%A3o-de-c%C3%B3digo-sql-no-meu-c%C3%B3digo-php?rq=1
Answer: O mysql_prepare evita SQLinjection, desde que, você utilize parâmetros na query.
Se você utilizar o mysql_prepare concatenado os valores dos campos com a query, não vai adiantar nada, porém, as funções mysql_* são consideradas obsoletas.
Eu indicaria você a utilizar PDO, é muito bom para trabalhar com banco de dados, e se um dia você precisar trocar seu banco de dados, será muito mais simples com PDO.
Comment: A pergunta é de mysqli_ e não mysql_. No caso PDO seria inferior ao perguntado (mysql_ sem o "i" é problema. PDO é melhor que mysql_, mas  mysql **i** _ é muito melhor que PDO para usar com MySQL pq foi feita pra isso, principalmente na parte de segurança, que não é só simulado concatenado igual PDO). A parte de usar parametro tá certinha. Sò precisa consertar a recomendação furada.
Answer:
The purpose of prepared statements is to not include data in your SQL statements. Including them in your SQL statements is NOT safe. Always use prepared statements. They are cleaner to use (code easier to read) and not prone to SQL injections.
Escaping strings to include in SQL statements doesn't work very well in some locales hence it is not safe.

Tradução:

O propósito das declarações preparadas é não incluires dados nas instruções de SQL
"Escapar strings" para se incluir em instruções SQL não funcionam em alguns casos, portanto não é seguro

Retirado de php.net
Comment: Apesar de sua boa itenção em ajudar, o idioma do site é português, e é esperado que tanto perguntas e respostas também seja, mesmo que sejam citações. Por isso, para não desqualificarem sua resposta com negativos, você poderia traduzir essa citação.


Prove there is no field F satisfying R ⊊ F ⊊ C

Question: I've (obviously) just learnt the basics of groups and fields and I've come across this exercise:
Prove there is no field $\mathbb{R} ⊊\mathbb{F} ⊊\mathbb{C}$. My reasoning is simply that since $\mathbb{F} \neq \mathbb{R} $ it must contain at least one complex number, say $x+yi$. So then it contains $(x+k) + yi$ for any real number $k$ and from there it contains $c(x+k) + cyi$ for some other real number $c$ so $\mathbb{F}$ would be equal to $\mathbb{C}$. However I am not sure if this qualifies as a "proof" or if this is right. Any help is appreciated!
Comment: Use tower law of field extensions. Since $\mathbb{C} $ is of degree $2$ (prime) over $\mathbb{R} $ this works out.
Comment: You want to assume $y\neq 0$ then write any $a+bi$ in terms of real reals and $x+yi.$
Answer: You are on the correct path, but I'd personally tidy that up a bit! Let your field $\mathbb{F}$ satisfy $\mathbb{R}\subsetneq\mathbb{F}\subseteq\mathbb{C}$. We will now show it has to be equal to $\mathbb{C}$.
As you mentioned, there is a complex number $x+yi\in\mathbb{F}$ with $y\neq0$. Notice that $x+yi-r$ and hence $\frac{x+yi - r}{s}$ are also in $\mathbb{F}$ for any reals $r, s$, with $s\neq0$ (can you tell me why?). Choosing the correct $r, s$, we may show that $i\in\mathbb{F}$, and then it will follow (why?) that $\mathbb{F}=\mathbb{C}$.
Comment: so if r = x and y = s then  ∈  so ---  ok yea it's pretty clear why F = C then, thank you!
Answer: Yes, You are on a right track... As someone said above you need to assume $y \neq 0$ then what you want to do is take any complex number z=a+ib and show that there exists some u and v such that u=c(x+k) and v=cy for some c and k in Reals.. can you do that? If you did that then your proof is complete ... do you understand why? let me know in the comments


Using Bayesian statistics to analyze food production

Question: I am in the process of learning about Bayesian statistics with the help of R, and I would like to know the kind of analysis questions I should pose.
Say for instance, with this dataset of food production in various countries. So far, I've just created simple linear regression models.
Comment: It is unclear what is your question about. If you ask "kind of analysis questions I should pose", than the answer is simple and useless: you should ask questions that are *relevant* to your problem...
Answer: If you are looking to stretch your wings a bit you might try picking up a book on bayesian analysis, maybe even written in a different language and work through some examples.
What immediately comes to mind would be:
R: Doing Bayesian Data Analysis
Python: Probabilistic-Programming-and-Bayesian-Methods-for-Hackers
If you are looking for relevant Bayesian questions in your work I suppose you need to provide more detail about what you do/are trying to do. This would be more of evaluating if a Bayesian Approach is relevant though.


UIView and AutoresizingMask ignored

Question: First time posting on stack overflow.
I've spent hours scouring over many Google searches and have, at this point, practically memorized the UIView and UIViewController class reference docs. No matter what I do, my app is ignoring my efforts to resize my views on orientation change (or any other frame size modifications for that matter.)
There are no nibs or xibs involved; I am building all of my views and viewcontrollers programmatically, and they (the viewcontrollers) are all subclasses of one of three custom UIViewController subclasses that I have created. These super classes have the following lines in their loadView: method...
[self setView:[[[UIView alloc] initWithFrame:[self viewFrame]] autorelease]];
[[self view] setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
[[self view] setAutoresizesSubviews:TRUE];

In all of the appropriate setter methods (wherever I add a subView in other words) I am repeating the steps of applying the autoresizingMask. It seems that no matter what I do, the outcome is always the same -- I click build, click debug, wait for the app to launch, rotate the device, and presto! The view rotates but does not resize at all.
What am I missing here? It's probably something obvious that I am just not seeing. Any help is truly appreciated, thanks in advance.
Answer: Well, sure enough, it was my own fault.
Lesson number one: You are not doing yourself any favors by staying up all night trying to fix broken code. Get some rest! Drink more water! You will only probably make things worse if you keep trying to force your brain to perform complicated algorithmic strategy and logic past its bed-time.
Turns out I had a rogue UIView toward the bottom of the view hierarchy that did not have the autoresize property set at all. I thought I had looked through everything, but turns out that I missed one. (Just one little view, and an entire day shot!)
I can say for anyone who comes along later with similar frustration, that Autoresizing does indeed work as documented. If you think that "something is not being called" then you are probably looking in the wrong place. Also, the UIViewAutoresizingMask enum constants are not used exactly like they are in Interface Builder. In IB, you "lock" margins, whereas in setting them programmatically, the locked margins are assumed by default and you "unlock" them by setting it as "Flexible". So for example, setting only the FlexibleWidth and FlexibleHeight bits is equivalent to enabling all autoresizing options in IB. By throwing in any of the margin masks (i.e. UIViewAutoresizingFlexibleLeftMargin) you are "deselecting" the corresponding margin autoresizing option in IB. (I've seen many other posts floating around where this seemed to be a major point of confusion for some folks.)
During my research, however, I did notice that there does not seem to be any sort of event, message, notification, or otherwise when a UIView gets resized, whether automatically or not. While not necessary for resizing subViews, it would be nice to know when it's happening in the situation where you would like to cause a scrollView or tableView to scroll should it's frame size ever change. I know one can easily do this when the keyboard pops up, because there is a notification system around that as well as the TextField delegate methods. So maybe a topic for another post...
Anyway, thank you everyone who participates on StackOverflow!
Comment: Overriding -setFrame: is a pretty reliable way to see that a view has resized.
Comment: Oh yeah, sure! I use that technique all the time when debugging retain counts, but I often overlook doing that in other situations such as this. (Funny how evasive the obvious can be.) To clarify your comment for others, this is referring to overriding -setFrame in order to spit up some NSLog that tells you the name of the view and some frame values. (Don't forget to call super's implementation if you try this.)
Comment: Other than that, I wouldn't use that method for anything else. I would also make dure to disable the override before releasing the code as production.
Comment: where do you override setFrame? The UIViewController or UIView subclass?
Comment: 'setFrame:' is on UIView. Also, if you need to know when it happens to any and all views, you can create a category method that affects all UIView and subclasses and logs the event. Again, I advise against using this method for any other purpose than temporary troubleshooting. Any updates to the content of a view should be handled by its view controller.
Comment: 1 up for "Lesson Number one" :)

UIView and AutoresizingMask ignored


how to open a link field in new window in view

Question: In views,for image  field, I have selected "output this field as link" and in link path, I wrote "node/[nid]". Link works and open in same window. How to open the link in a new window? I dont see any option in view.
Thanks
Answer: 1) Click your image field at your views
2) Click Rewrite results. Check Output this field as a link. Key in your URL in the Link Path

) 3) At Target text field, key in this "_blank"
Comment: I have the same problem but this solution does not work!! is there any other way?
Comment: I glad it help. Do you mind give me vote up? Lol
Comment: May I know what you key in the link path and what is the option you choose for formatter?
Comment: my link path is the token of image field and formatter is just image
Comment: Similar approach on Drupal 8, where `[nid]` turns into `{{ nid }}`
Answer: To do so programmatically, you need to define ThemeName_preprocess_views_view_fields function. Then in this function you should theme the views output. If the image field name is field_image then write:
function ThemeName_preprocess_views_view_fields(&$variables)
{
      $view = $variables['view'];
      if($view->name == "TheViewName")
      {
           $variables['image'] = $variables['fields']['field_image']->FIND THE IMAGE PATH BY DEVEL MODULE;
           $variables['link'] =  $variables['fields']['field_image']->FIND THE IMAGE LINK ADDRESS BY DEVEL MODULE;
      }
}

Then create views-view-fields--TheViewName--DisplayNameOfView.tpl file and in this file write
$image = strip_tags($image) ;
<a href="<?php print $link?>" target="_blank"><img src="<?php print $image;?>"

Notice that you should install devel module to get required information about the image, its link and etc.
Clearly in this method you will have more choices of displaying the link and you can also use this method to open the image in a popup window.
This is the main idea of doing this and I always use this. I didn't test this code but a few modification might be needed. for example in  views-view-fields--TheViewName--DisplayNameOfView.tpl you can use <?php print $fields['field_image']->content; ?> to output the entire linked image.


Running tor on lxc-based virtual infrastructure

Question: I tried to set up a tor relay node on my server running debian squeeze with linux containers for better maintainability. Installing from main repository and tor repository failed. In debug.log there is only one error message:
Sep 20 21:24:12.402 [notice] Tor 0.2.2.39 (git-2f7e71c2e896772f) opening log file.
Sep 20 21:24:12.402 [info] tor_lockfile_lock(): Locking "/var/lib/tor/lock"
Sep 20 21:24:12.402 [debug] parse_dir_server_line(): Trusted 4 dirserver at 18.104.22.168:9131 (9695)
Sep 20 21:24:12.402 [debug] parse_dir_server_line(): Trusted 15 dirserver at 184.108.40.206:80 (847B)
Sep 20 21:24:12.402 [debug] parse_dir_server_line(): Trusted 6 dirserver at 188.8.131.52:80 (7EA6)
Sep 20 21:24:12.402 [debug] parse_dir_server_line(): Trusted 16 dirserver at 188.8.131.52:80 (4A0C)
Sep 20 21:24:12.402 [debug] parse_dir_server_line(): Trusted 4 dirserver at 220.127.116.11:9030 (F397)
Sep 20 21:24:12.402 [debug] parse_dir_server_line(): Trusted 4 dirserver at 18.104.22.168:80 (F204)
Sep 20 21:24:12.402 [debug] parse_dir_server_line(): Trusted 4 dirserver at 18.104.22.168:80 (7BE6)
Sep 20 21:24:12.402 [debug] parse_dir_server_line(): Trusted 4 dirserver at 188.8.131.52:443 (0AD3)
Sep 20 21:24:12.402 [debug] parse_dir_server_line(): Trusted 4 dirserver at 126.96.36.199:443 (BD6A)
Sep 20 21:24:12.402 [info] or_state_load(): Loaded state from "/var/lib/tor/state"
Sep 20 21:24:12.402 [info] circuit_build_times_parse_state(): Adding 0 timeouts.
Sep 20 21:24:12.402 [info] circuit_build_times_parse_state(): Loaded 0/0 values from 0 lines in circuit time histogram
Sep 20 21:24:12.402 [info] read_file_to_str(): Could not open "/var/lib/tor/router-stability": No such file or directory
Sep 20 21:24:12.402 [err] /dev/null can't be opened. Exiting.

I have full access to /dev/null in the container, for example
dd if=/home of=/dev/null

works proper.
Config of the lxc container is with option
lxc.tty = 4
lxc.pts = 1024
lxc.rootfs = /var/lib/lxc/tor/rootfs
lxc.cgroup.devices.deny = a
# /dev/null and zero
lxc.cgroup.devices.allow = c 1:3 rwm
lxc.cgroup.devices.allow = c 1:5 rwm
# consoles
lxc.cgroup.devices.allow = c 5:1 rwm
lxc.cgroup.devices.allow = c 5:0 rwm
lxc.cgroup.devices.allow = c 4:0 rwm
lxc.cgroup.devices.allow = c 4:1 rwm
# /dev/{,u}random
lxc.cgroup.devices.allow = c 1:9 rwm
lxc.cgroup.devices.allow = c 1:8 rwm
lxc.cgroup.devices.allow = c 136:* rwm
lxc.cgroup.devices.allow = c 5:2 rwm
# rtc
lxc.cgroup.devices.allow = c 254:0 rwm
# mounts point
lxc.mount.entry=proc /var/lib/lxc/tor/rootfs/proc proc nodev,noexec,nosuid 0 0
lxc.mount.entry=devpts /var/lib/lxc/tor/rootfs/dev/pts devpts defaults 0 0
lxc.mount.entry=sysfs /var/lib/lxc/tor/rootfs/sys sysfs defaults  0 0
# network
lxc.utsname = tor
lxc.network.type = veth
lxc.network.flags = up
lxc.network.link = br0
lxc.network.ipv4 = 172.24.18.14

So, does anybody got an idea whats wrong there?
Comment: Also, you should actually check the ownership and permissions of `/dev/null` in the container. You can do this with `ls -l` and edit the question to show your results.
Comment: I am really _not_ trying to waste your time. You _absolutely_ should double check this. In practice I have had about ⅓ of my LXC containers somehow wind up with a trashed `/dev/null`.
Answer: Ok, i got it... the permissions inside the LXC is different to the hosts permisssons.
While the host has 0666 on /dev/null, the container has read-only access.
It is a bit strange because the lxc config file has something like
lxc.cgroup.devices.allow = c 1:3 rwm

for /dev/null.
Thank you Michael


Como posso fazer um objeto se 'auto-deletar' em JavaScript?

Question: Tentei algo como:
function Objeto(){
  this.del = function(){
    delete this;
  }
}

var a = new Objeto();

a.del();

Mas a variável a ainda está existindo

Eu conheço o método citado na resposta do @bfavaretto, mas para o código em que estou trabalhando não consigo 'subir um nível' na estrutura de variáveis para executar este delete, ou obj = null;
Eis o trecho em que pretendo utilizar isto:
Bullet.prototype.step = function() {
    for (var i = 0; i < mobs.length; i++){
        if ((this.x >= mobs[i].x && this.x <= mobs[i].x + mobs[i].size) && (this.y >= mobs[i].y && this.y <= mobs[i].y + mobs[i].size)){
            mobs[i].getHit(this.damage);
            delete this;
        }
    }
};

Ou a referência completa:http://codepen.io/GabrielMaia/pen/LEmROB
Comment: Então tudo que precisa ser feito é remover essa bala da array. Crie uma função para isso, que receba a bala em questão e remova a posição correspondente da array. Você pode encontrar a posição com `indexOf`, e remover com `splice`.
Comment: Ok @GabrielMaia, que bom que funcionou! Atualizei minha resposta para concentrar a informação num único lugar.
Comment: Gabriel, o problema é que o `delete` não deleta o objeto e sim uma propriedade de um objeto. Se você testar: `window.teste = new Object(); delete window.teste;`, perde-se a referência para o `teste` mas se alguém tiver uma referência pra ele, é possível acessá-lo.
Comment: Pode explicar melhor por que você está querendo fazer isso?
Comment: É o básico de um sistema de projéteis em um jogo simples...
Quando uma _bullet_ entra em contato com um _mob_ ela deveria sumir, porque quando muitas dessas são carregadas a perda de desempenho é visível... Pretendo fazer com que ao encontrar um _mob_, ou os limites da tela, _bullet_ se destrua, dando lugar a uma nova _bullet_ no array _bullets_
Comment: It Works \o/
Funcionou perfeitamente com esses métodos, fico muito grato.
Answer: Você pode simplesmente definir todas as referências ao objeto como null:
a = null;

Mas precisa ser todas mesmo. Por exemplo:
var b = a;
a = null;
b = null; // não esqueça!

Pergunta relacionada: Como funciona o coletor de lixo do JavaScript?

Considerando seu comentário que diz se tratar de uma array de bullets, de onde você precisa retirar uma dessas balas: crie uma função para isso, que receba a bala em questão e remova a posição correspondente da array. Você pode encontrar a posição com indexOf, e remover com splice. Algo assim:
var bulletArray = []; // considere populada
function removeBullet(bullet) {
    var index = bulletArray.indexOf(bullet);
    bulletArray.splice(index, 1);
}


Redirect to Different URl on validation errors in form builder

Question: I am using drupal 8 fapi and i have user case as below
I have a form  on https://example.com/landing-page and I submit the  form and there are validation errors .the page should reload as https://example.com/landing-page#lead-form.
Is there any hack we can implement?
I came with logic
if validation has error set form redirect page to example.com/landing-page#lead-form
if($form_state->getErrors() ) {
  $response = new TrustedRedirectResponse('example.com/landing-page#lead-form');
  $form_state->setResponse($response);
}

some how its not working.
Is there any way we can change the url to example.com/landing-page#lead-form and show the validation error at same time .
Comment: @jaypan if you can help me on this
Answer: You can use like
For Internal:
global $base_url;
$response = new TrustedRedirectResponse($base_url.'/landing-page#lead-form');
// You can use any one of these below to show error message.
$form_state->setError($element, $message);
$form_state->setErrorByName($element, $message);
$form_state->setResponse($response);

For External:
Use full link
$response = new TrustedRedirectResponse('https://facebook.com');
// You can use any one of these below to show error message.
$form_state->setError($element, $message);
$form_state->setErrorByName($element, $message);
$form_state->setResponse($response);

Answer: You can use EnforcedResponseException to terminate form processing and redirect:
$response = new RedirectResponse(Url::fromRoute('user.login', [], ['absolute' => TRUE])->toString());
throw new \Drupal\Core\Form\EnforcedResponseException($response);

For external urls use TrustedRedirectResponse not RedirectResponse:
$response = TrustedRedirectResponse('http://www.google.com');
throw new \Drupal\Core\Form\EnforcedResponseException($response);


ajax - submit form with ajax 2

Question: Noting happened on submit. why is that?
<code><button id="submitRegButton" class="btn btn-success">SEND</button>

$(document).on('#submitRegButton','form',function(e) {
.....
});
</code>
Comment: your syntax is wrong. check this docs http://api.jquery.com/on/
Answer: Your syntax is wrong.
Try this
<code>$(document).on('click','#submitRegButton',function(e) {
     alert("button click");
});
</code>

ajax - submit form with ajax 2


How to manage git repository that contains projects with different release times?

Question: As is, I have a visual studio solution which contains multiple projects including a website, a desktop app, a library, and some periodic reporting applications. The git repository is at the solution level, so it covers all the projects. Now, I am actively working on a new, big part of the website, so there are many changes in the library and website. All these changes exist on their own. Likewise, all the changes for the desktop app exist on its own branch. When I want to release a new version of the website or the desktop app, I just build it from the respective branch. However, the library project has diverged a bit between the desktop app branch and the website branch.
So what's the better way to handle this? Should I merge the branches all into one? At this point, that would probably result in a huge amount of conflicts. Or should I be using different repositories for every project maybe?
Answer: There are different approaches for this problem.
Merging is not ideal as it will not solve the purpose.
Different Repo's looks the good way to move forward.
like
<code>[yourPrjoectName]Desktop
[yourPrjoectName]Web
[yourPrjoectName]Common etc.
</code>
In this way you have different owner for different repos etc.


How to find the maximum distance between two paths over a time interval (diff eqn) AP Calc Question

Question: Alice and Bob go for a jog in the same direction along a straight path. For $0\leq t \leq20$, Alice's velocity at time t is given by $A(t)=\frac{6010}{t^2-3t+50.5}$ meters per minute, and Bob's velocity at time t is given by $B(t)=8.5t^3e^{-0.45t}$ meters per minute. Both of these velocities are always positive. Alice is 12 meters ahead of Bob at time $t=0$, and she remains ahead of Bob for $0\leq t\leq 20$.
What is the maximum distance between Alice and Bob over the time interval $0\leq t \leq 20$?
The answer is $d=1413.23$ when $t=4.58$.
I'm confused on how to get this answer...
I did $\int_0^{20} \frac{6010}{t^2-3t+50.5} - \int_0^{20} 8.5t^3e^{-0.45t}$
$\int_0^{20}\frac{6010}{t^2-3t+50.5} =1232.323$
$\int_0^{20} 8.5t^3e^{-0.45t}=1217.313$
and got $1232.323-1217.313=15.01=d$
I thought that the distance between Alice and Bob is $\int A(t)-\int(B(t)$ so I'm confused where I went wrong.
How can I solve this?
Comment: You've got some elements correct, but how did you get from the difference in the integrals to $t \approx 15.05 $? The issue will be somewhere between those two statements, so if you show us your work, we can help pinpoint what went wrong.
Comment: thanks, i just updated it with what I did
Answer: You've calculated the overall difference in the distances they traveled between $t=0$ and $t=20$, not the difference at a specific point in time. What we need is the difference as a function of $t$.
We're given $A(t)=\frac{6010}{t^2-3t+50.5}$ meters per minute, and $B(t)=8.5t^3e^{-0.45t}$. Since we know Alice is ahead of Bob at any given time, and we know that at $t = 0$ Alice is $12$ meters ahead of Bob, we can write our distance function as follows:
$$ d(t) = 12 + \int_0^t A(\tau) - B(\tau) d\tau $$
This is similar to what you wrote, except you integrated from $\tau=0$ to $\tau=20$. Now, the key to this problem is that we want to maximize that distance, so all we have to do is differentiate and set the derivative equal to $0$, which is very easy with the Fundamental Theorem of Calculus:
$$ \frac{d}{dt} d(t) = \frac{d}{dt} \left( 12 + \int_0^t A(\tau) - B(\tau) d\tau \right) = A(t) - B(t)$$
$$ \Rightarrow A(t) - B(t) = 0 $$
$$ \Rightarrow A(t) = B(t) $$
$$ \Rightarrow \frac{6010}{t^2 - 3t + 50.5} = 8.5t^3e^{-0.45t} . $$
We can use a calculator to solve numerically and find that $A(t) = B(t)$ at $t \approx 4.584$ or $t \approx 16.715$. These are the local extrema on the interval $t\in [0,20]$, so plug those values back into $d(t)$, plus check the endpoints at $t = 0$ and $t = 20$, and one of those four values will be your maximum distance.
Comment: Thank you so much! Just one more question: when I do $d(4.584)=12+\int_{0}^{4.584} A(\tau)-B(\tau) d\tau$ I get 365.527. But this is wrong?
Comment: Hmm, I'm seeing the same thing. The max still occurs at $t = 4.584$. Are you sure you've copied the functions exactly as they were in the problem? And that the answer source should be correct?
Comment: I'm 100% sure I copied the question correctly however the answer source might not be correct. So just to double check with you for $t=0,d=0,$, and $t=4.584, d=365.527$ and $t=16.715, d=13.344$ and $t=20, d=27.01$
Comment: if we both got the same thing then the answer source must be wrong
Comment: At $t = 0$, you should have $d = 12$, don't forget your initial condition! I have the same answers for everything else.
Comment: oh right! yes thank you so much for all of your help. I understand now
Comment: You're very welcome!


O que pode ser o erro?

Question: FAILURE: Build failed with an exception.

* What went wrong:
Could not determine the dependencies of task ':app:compileDebugJavaWithJavac'.
> Could not create service of type AnnotationProcessorDetector using JavaGradleScopeServices.createAnnotationProcessorDetector().

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 1s
Finished with error: Gradle task assembleDebug failed with exit code 1

Comment: Rode com `--stacktrace` e coloque a saída para analisarmos. Conforme o que formos concluindo vamos solicitar algum trechos de código para verificação. OK?
Answer: Segundo essa issue do Github, faça:
./gradlew compileJava recompile --stacktrace

Segundo esta issue tente: gradle --stop depois: gradle --test para reiniciar.
Se não funcionar tente:
Remover o diretório .gradle (linux):
./gradlew --stop
sudo rm .gradle/4.10.1/javaCompile/classAnalysis.bin
rm -r build
rm -r app/build
sudo chown [username] .gradle/4.10.1/javaCompile
sudo chown [username] .gradle/4.10.1/javaCompile/*
./gradlew build

No windows você pode remover manualmente.
Se não funcionar tente o que este pessoal recomenda:
Dê um --stacktrace --info para coletar mais informações sobre o problema, caso não encontre solução.

O que pode ser o erro?


Is there a line in space that doesn't intersect any body

Question: Say we model our universe as an infinite space with planets that are all spheres of the same size, uniformly distributed through-out with some fixed density.
Is it then true that any infinite line in that space must eventually intersect one of those planets? Does the result depend on the density?
If it matters, I would like to ignore the possibility that due to the random position of each planet, there could theoretically be a line that intersects none of them.
My intuition tells me that the answer is yes because I can imagine examples where the spheres are big enough and dense enough that two "rows" of them would block out the sky with no holes between.
However, I feel like it might be possible that for some low density, the angular size of the planet diminishes just enough (with distance from our origin) that the increased number of planets that are at that distance doesn't compensate for it.
I don't know what to tag this question with. Would appreciate an edit that adds the correct tags.
Answer: Unless we know exactly where every planet is, we cannot answer this question. But what we can say is that if the density is uniform (however small) the probability that any line intersect a planet is $1$.
To see why, subdivide the line into equal segments (say $1000$ km per segment). Then, for each segment, the probability that a planet intersects the segment is some non-zero number $p>0$ that depends on the density. Now, since we repeat the same experiment independently for infinitely many segments, the probability that a planet intersects at least one of them is 1.
Comment: Nice! That makes complete sense.


plot raster factor values with ggplot

Question: I have problems plotting a raster with factor values using ggplot2.
library(ggplot2)
library(raster)

first, load raster data
f <- system.file("external/test.grd", package="raster")
r <- raster(f)

extract coordinates and values
val <- getValues(r)
xy <- as.data.frame(xyFromCell(r,1:ncell(r)))
xy <- cbind(xy,val)

plot the grid using geom_raster(). Everything works fine.
ggplot(xy, aes(x=x, y=y, fill=val)) + geom_raster() + coord_equal()

I don not have a continuous raster, but a classified. Reclass the raster:
r <- reclass(r, c(0,500,1, 500,2000,2))

val <- getValues(r)
xy <- as.data.frame(xyFromCell(r,1:ncell(r)))
xy <- cbind(xy,val)

plot the classified raster. Also OK, but legend is continuous
ggplot(na.omit(xy), aes(x=x, y=y, fill=val)) + geom_raster() + coord_equal()

if I plot the values as factor, the map becomes wrong
ggplot(na.omit(xy), aes(x=x, y=y, fill=factor(val))) + geom_raster() + coord_equal()

Answer: Plotting the reclassified plot works for me using R version 2.15.1, ggplot2_0.9.2.1 and raster_2.0-12. If applicable, try updating R, packages, and dependencies. Proceeding from a slightly modified version of your code:
f <- system.file("external/test.grd", package="raster")
r <- raster(f)
r <- reclassify(r, c(0,500,1, 500,2000,2))
val <- getValues(r)
xy <- as.data.frame(xyFromCell(r,1:ncell(r)))
xy <- cbind(xy,val)
ggplot(na.omit(xy), aes(x=x, y=y, fill=val)) + geom_raster() + coord_equal()
p <- ggplot(na.omit(xy), aes(x=x, y=y, fill=factor(val))) +
  geom_raster() +
  coord_equal()
try(ggsave(plot=p,<some file>,height=8,width=8))

I get:

Note that classify() has been depreciated and reclassify() is its substitute.

plot raster factor values with ggplot


Are these formulas equivalent?

Question: I am solving the problem from the textbook, and g) part states "There is exactly one person whom everybody loves." L(x, y) is "x loves y."
(1) The first and easiest solution is: $\exists !y\forall xL\left(x,y\right)$
(2) Then I came up with the second solution:
$\exists \:y\left(\forall \:x\left(L\left(x,\:y\right)\:\wedge \forall \:z\left(L\left(x,\:z\right)\rightarrow \left(z=y\right)\right)\right)\right)$
Which I think is also the correct one.
(3) The third solution is: $\exists x\left(\forall yL\left(y,\:x\right)\:\wedge \forall z\left(\left(z\ne x\right)\rightarrow \exists w\neg L\left(w,z\right)\right)\right)$
(4) And the solution from the book is: $\exists x\left(\forall yL\left(y,x\right)\wedge \forall z\left(\left(\forall wL\left(w,z\right)\right)\rightarrow z=x\right)\right)$
Is the (2) second formula correct in this case? and if so, are they equivalent?
Comment: They don't have a lot of differences, but as we can see there is additional  ∀w in (4), which I think is unnecessary, and we can use only ∀x as (2) one shows us.
Comment: #4 is just a full translation of #1 (since the "unique existence" quantifier can be expressed in terms of the standard existential and universal quantifiers), and #3 is just contrapositive applied to #4. The only one that is truly wrong is #2, as the provided answer explains (it says there exists a person which is loved by everyone and is the only person anyone loves)
Answer: No, it is not correct. $\forall z (L(x,z) \rightarrow (z=y))$ means that if someone loves $z$, that person must be person $y$. Which means that someone can only love person $y$ and no one else. However, "There is exactly one person whom everybody loves." means that there is one person loved by everybody and no other person is loved by everybody. This does not imply that everyone only loves 1 person, which is what you encoded in your formula.
The difference with eq. 4 is that it is now stated that: "if someone is loved by everyone, the person must be person z.". Note that this does not state that everyone only loves 1 person. The forall part is necessary in this case.
A good way to see if you translation is correct is to translate your formula back to English and see how well it matches the original sentence.
Comment: I read your entire answer, and I agree with you that it's useful to try translate the formula to English, but if we do so, then we will see that they are the same.
The (2) one states: There exists y for all x such that every x loves y and for every pair x and z, if x loves z, then z equals y. If I have any incorrect conclusions let me know ;)
Comment: The commenter on your original post provided an excellent translation to English. Using that translation it'll be easier to understand why your formula does not match the original statement.
Comment: So as I understand I wrote something like "Every person likes y and one y.", didn't it?
Comment: If you change "one" to "only", yes
Comment: Yes, it's just a typo, again thanks a lot :)

Are these formulas equivalent?


Aplicar estilo a table em javascript

Question: Tenho uma table

Estou carregando ela dinamicamente através do resultado de um AJAX:
 var myData = result
            for (var i = 0; i < myData.length; i++) {
                var obj = myData[i];

                rows += "
";
                rows += "Id	";
                rows += "Nome	";
                rows += "
";
                rows += "
";
                //rows += " " + obj.id + "	";
                rows += " " + obj.id + "</>";
                rows += " " + obj.nome + "	";
                rows += "
";
            }

E tentando aplicar o estilo:

Porém não funciona, como devo fazer para carregar o estilo?
Answer: Acho que é porque depois do th (titulo da tabela) vc tenha que usar o td ( celula padrão) que está chamando no estilo.
E tem um fechamento da tag que você não colocou:
rows += "
";
            //rows += " " + obj.id + "	";
            rows += " " + obj.id + "	";
            rows += " " + obj.nome + "	";
            rows += "
";

Comment: Funcionou @Douglas , Valeu pela ajuda!

Aplicar estilo a table em javascript


Hibernate update is sometimes not working

Question: I have a requirement where I am updating rows according to uuid's where one uuid may be associated to more than one rows.
Here's the scenario:
4a90558c-4a5b-4af7-8c68-60ff81f74ef3 is my uuid and it exists in 8 columns in my DB.
and my java code is as follows:
    try{
        session = sessionFactory.getCurrentSession();
        tx = session.getTransaction();
        criteria = session.createCriteria(Archive.class);
        criteria.add(Restrictions.eq("bagUuid",  "4a90558c-4a5b-4af7-8c68-60ff81f74ef3"));
        ScrollableResults items = criteria.scroll();

         while ( items.next() ) {
             Archive archive = (Archive)items.get(0);
             archive.setDecision(1);
             archive.setOperatorAssigned("test");
             session.saveOrUpdate(archive);
             session.flush();
             session.clear();
         }
         tx.commit();
        LOGGER.info("Archive Record is updated: "+archive.getFilePath());
    }catch(Exception e){
        recordUpdated = false;
        tx.rollback();
        LOGGER.error("Archive Record failed to update due to exception in updateArchiveRecord method: "+e.getMessage());
    }

Here sometimes all records associated to UUID is updating but sometimes failing.
I think it may be a issue with the Hibernate API.
Does anybody else has faced the same issue.
Comment: If somebody told you that something failed, what would be your next question? Most probably it would be: In which way did it fail? Did it ignore the updates or threw an exception? In case it is an exception, what would you ask next? Probably: Which exception?
Comment: use an `e.printStackTrace();` in catch
Comment: No exceptions at all. sometimes it updates 8, sometimes 2 and sometimes 3
Answer: This line looks suspicious:
Archive archive = (Archive)items.get(0);

It means thart regardless of the number of items in the ScrollableResults, you will be updating only the first Archive object. If I understood what you are trying to do correctly, it should be a current record:
Archive archive = (Archive)items.get();

Also, I'd move out/delete session.flush() and session.clear(). The final code would look like this:
try{
    session = sessionFactory.getCurrentSession();
    tx = session.getTransaction();
    criteria = session.createCriteria(Archive.class);
    criteria.add(Restrictions.eq("bagUuid",  "4a90558c-4a5b-4af7-8c68-60ff81f74ef3"));
    ScrollableResults items = criteria.scroll();

     while ( items.next() ) {
         Archive archive = (Archive)items.get();
         archive.setDecision(1);
         archive.setOperatorAssigned("test");
         session.saveOrUpdate(archive);
     }
     tx.commit();
     session.close();
    LOGGER.info("Archive Record is updated: "+archive.getFilePath());
}catch(Exception e){
    recordUpdated = false;
    tx.rollback();
    LOGGER.error("Archive Record failed to update due to exception in updateArchiveRecord method: "+e.getMessage());
}

Slava Imeshev


Tree with Multiple Children - Linear Time Access Complexity

Question: My problem is not with the structure to hold the Tree but the way I am doing it; because I think this implementation will cost much in long run.
I have a tree structure in which a tree Node will contain the List of references of its children. But here the problem is that while finding the child of a Node, we need to go through the List of children which will take Linear time(Linear time complexity). And I also need to store these all as immediate child(as children word is used for the immediate children).
Now, is there any way I can put all the children other than List structure so that the retrieval and deletion of the children from the List will be efficient and logarithmic(if we can)?

If I am going to traverse the Tree then to go to the right children from the root node, I will have to check a condition for each child node. That check would be Linear search and check.
I just want a technique which will help in improving this algorithm of searching for the right child in the children list during traversal.
Comment: you need to be more descriptive about your data structure, how many children can a node have, is it a by definition tree, or a you using the term tree incorrectly
Answer: Instead of just having each node keep a regular list, have it either keep a sorted list(log n lookup) or a hashmap(constant time lookup). In this case sorting is probably the best so you can easily iterate over the elements and save space.
Comment: That applies in a case where a Node contains a string or int so that I can sort and perform Binary Search/Divide and Conquer algo to find the element in Logarithmic time.
Comment: @MasterJ well your node has to have some sort of data in it, if it has data you can sort it
Comment: Yes, But in my case I am just holding the references of the Nodes which does not have anything to get sorted.

Creating any priority attribute in the Nodes will diminish my work of holding references that is why I can not have such a sorting element.
Comment: @MasterJ you can pretty much always have a sorting criteria, but once ur talking about references you have to specify a language for further help
Comment: I will add the children dynamically using a UI.

Like I have selected a Node then then I select its children by dragging and dropping just below it. Doing this parent Node will hold the list of references of all the Nodes added to it.

I will do it this way that is why the references can not have any sorting information.
Comment: @MasterJ well I still don't see why that means you can't sort it, but if your just dragging and dropping these nodes speed isn't gonna matter much
Comment: I think I do need to keep a string with the Node where I will need to implement divide & conquer. Let me implement it.'
Comment: @MasterJ then sort or hash on that


Tetration of $\pi$: Can it be a prime number?

Question: Given the tetration as
\begin{align}
{^{n}a} = \underbrace{a^{a^{\cdot^{\cdot^{a}}}}}_n
\end{align}
and the set of prime numbers as $\mathbb{P}$.
Can you prove or to disprove the following statement?
\begin{align}
\forall p\in\mathbb{P}:(^{p^2+1}\pi)\in\mathbb{P}
\end{align}
I tried to disprove it, but I failed to do it.
Thank you
Comment: I think to check whether $^n \pi$ is an integer is hard enough.
Comment: If you tried, what did you try? It seems unlikely (but certainly possible) that no $^n\pi$ is ever even rational, much less prime.
Comment: Initially, I played around by searching some rules about $^n\pi^$ for small $n$, but I did not find anything. Computing some values also failed (if the statement is wrong this would probably the easiest way to disprove it).
Answer: I believe that nothing close to this is known currently; see e.g. this answer and the ensuing discussion. There are lots of "basic" problems about integrality/nonintegrality, rationality/irrationality, algebraicity/transcendence, etc. which are wide open.
There are many number-theoretic conjectures with good heuristic evidence which are known to resolve many such questions, but I don't know of any which would resolve this particular one. I suspect that all heuristics currently known suggest that $^n\pi$ cannot even be an integer for $n\in\mathbb{N}$ (number theorists, correct me if I'm wrong about this), but I don't think we're anywhere close to proving that or any related claim. Even numerical evidence is hard to come by: $^4\pi$ is already so huge that we don't obviously have a method to check experimentally whether it "looks like" an integer.

EDIT: Adding to address questions along the lines of xakepp35's comments below, the order of exponentiation matters. For example, $$2^{(2^{(2^2)})}=2^{16}=65536$$ but $$(2^2)^{(2^2)}=4^4=256.$$ Of course the latter is much easier to calculate, and it's not hard to show that $(\pi^\pi)^{(\pi^\pi)}$ is not an integer.
Given that it's so intractable, why to people care about tetration? Well, many don't - it certainly doesn't have any real-world applications I know of, and it's a very niche topic in pure mathematics. It is however a simple example example of a very fast-growing function, and the general study of fast-growing functions (indeed, ones much faster than tetration) is quite interesting; they arise in Ramsey theory and proof theory, for example. (That first link is to Graham's number, which is unspeakably gigantic; it's definitely worth a read.)
Comment: @xakepp35 Your first equation is wrong: it's $$\pi^{(\pi^{(\pi^\pi)})},$$ which is much larger. E.g. for contrast, consider the case of $2$: we have $$(2^2)^{(2^2)}=2^{2\cdot 2^2}=2^8=256$$ but $${}^42=2^{(2^{(2^2)})}=2^{(2^4)}=2^{16}=65536.$$ At a glance, I think ${}^4\pi$ is indeed computationally infeasible (although I'm not an expert of course).
Comment: @xakepp35 I'm sorry, but you're incorrect. "In computer science first is more useful, second is nowhere encountered." **But that's completely irrelevant**. First of all mathematics isn't subordinate to computer science: just because something isn't useful to CS doesn't mean it's not mathematically interesting. (For example, check out [Graham's number](https://en.wikipedia.org/wiki/Graham%27s_number), which makes tetration look *tiny*.) And this is a math question. (cont'd)
Comment: Why not check that 4^pi on a computer? Would not the value fit in a.. say it, 256GiB of RAM on a typical (older) server hardware?
Comment: 1) `pi^pi^pi^pi = (pi^pi)^(pi^pi)`, so we have to 2) calculate pp=pi^pi, which is 36,462159607 and put it to large enough memory cell. How large? well, lets estimate `bits` for integer part: `ln(2^bits)=ln(pp^pp))` so `bits = pp/log_base_pp(2)`. So kinda 190 bits will be enough to store integer part of `tetration(pi,4)`. Then, quadruple this amount and take 1 kilobyte to avoid any losses.. Take same amount for mantissa. Take bigint library.. go! what's the problem?
Comment: What is an operation, where you raise base to a power first? Eg we can have 2 constructions - of 3,3. First should give you 27^3, second is 3^27. In computer science first is more useful, second is nowhere encountered. So I think you have wrong order and it thus overflows.
Comment: Imagine Mandelbrot fractal process. You first raise Z to power 2 then add some C. And you got this very complex shape. Sane here . you may raise pi to pi first. Got new base, raise it to pi again, and then again. Resulting number is not so big, and it is irrational. And you may call it a power tower off, because it is a repeating process of raising to same power
Comment: Whether you're interested in it or not, this question is indeed about [tetration](https://en.wikipedia.org/wiki/Tetration) (read the title of the question). If you aren't convinced, you should turn your comments into an answer and see what feedback you get, or ask a new question about the definition and interesting-ness of tetration. But comments aren't for extended discussion, so I won't respond *here* further (although I will answer a question by you on the topic, should you post one).


Problema de organização do conteudo

Question: Ola
Eu tenho quatro selects e cada select tem o seu determinado titulo, mas eu estou com um problema apesar de eu no HTML ter o titulo em cima do select e em baixo de um botão, o titulo do select aparece em cima do botão ao centro e eu gostava que esse titulo volta-se ao sitio dele, alguem sabe como resolver este erro?

<button id="filtroselects">
   Filtros
</button>

<form id="selectsfiltro">

Faixa Etaria:

    <select id="FaixaEtaria" class="custom-select">
        <option></option>
        <option value="1">0-17</option>
        <option value="2">18-25</option>
        <option value="3">26-35</option>
        <option value="4">36 ou mais</option>
    </select>

Sexo:

    <select id="Sexo" class="custom-select">
        <option></option>
        <option value="5">Masc</option>
        <option value="6">Fem</option>
    </select>

Recurso a arma:

    <select id="RecursoArma" class="custom-select">
        <option></option>
        <option value="7">Sim</option>
        <option value="8">Não</option>
    </select>

Localidade:

    <select id="Distrito" class="custom-select">
        <option ></option>
        <option value="9">Viana do Castelo</option>
        <option value="10">Vila Real</option>
        <option value="11">Bragança</option>
        <option value="12">Braga</option>
        <option value="13">Porto</option>
        <option value="14">Aveiro</option>
        <option value="15">Viseu</option>
        <option value="16">Guarda</option>
        <option value="17">Coimbra</option>
        <option value="18">Castelo Branco</option>
        <option value="19">Leiria</option>
        <option value="20">Lisboa</option>
        <option value="21">Santarém</option>
        <option value="22">Portalegre</option>
        <option value="23">Évora</option>
        <option value="24">Setúbal</option>
        <option value="25">Beja</option>
        <option value="26">Faro</option>
        <option value="27">Açores</option>
        <option value="28">Madeira</option>
    </select>
</form>

CSS:

 #filtroselects {
       background-color: rgba(000, 000, 000, 0.0);
       color: white;
       border: 0;
       cursor: context-menu;
       margin-bottom: 10px;
       margin-left: -8px;
       font-size: 25px;
       float: left;
       margin-top: 30px;

   }
Comment: Já tentou usar labels?
Comment: David sem seu CSS não da para te ajudar muito, pq se vc executar esse Snippet ai da sua pergunta vc vai ver que fica tudo certo, então o problema é no CSS e não no HTML, Edite sua pergunta e inclua o CSS tb sem ele não da para te responder
Comment: @hugocsl o unico css que tenho foi esse que la pus o resto dos ids sao usados com scripts para os selects e algumas funções funcionarem, isto só ficou assim depois de termos colocado umas funções para telemovel, mas supostamente so devia editar em telemovel, não existe nenhum codigo que eu possa por para que o titulo do select fique em cima do select automaticamente?
Comment: @Afonso não, eu tambem não sei o que é isso.
Comment:  Fechas esse div?
Comment: @Pbras Sim essa div so serve para fazer um script para telemovel não tem muito a ver com o select para computador, devo ter esquecido de fechar quando copiei o select para o site.
Comment: Ok, experimenta mudar o dysplay do ``````, https://www.w3schools.com/cssref/pr_class_display.asp sem usar o web inspector não sei qual o melhor para meteres ai mas deve de haver um que resolve esse problema, experimenta os seguintes, flex, inline, block, grid, só adicionar um ```style="display=XXX;"``` ai para exprimentar com esses valores, depois diga se algum desses ajudo.
Answer: Já que vc falou que esse CSS é o único usado no documento, acredito que basta tirar o Float:left do CSS do Button que vai resolver.
Comment: Está certo! Obrigado!!
Comment: @DavidMv sem problemas meu caro!

Problema de organização do conteudo


How to make a text field box appear after clicking select option by using ajax?

Question: I created a content type with a select field whose options are the following ones.

Text
Text area
File

When I select Text area (*text), a text area box (a text box) should appear below the select field. When I select File, a button should appear after the select field.
I heard this can be done using AJAX, but I don't know where to start and how to do it.
Answer: You can use the Conditional Fields module, which allows you to show/hide fields based on other field's values.
From the module description:

Conditional Fields allows you to manage sets of dependencies between fields. When a field is "dependent", it will only be available for editing and displayed if the state of the "dependee" field matches the right condition.
When editing a node (or any other entity type that supports fields, like users and categories), the dependent fields are dynamically modified with the States API.
A simple use case would be defining a custom "Article teaser" field that is shown only if a "Has teaser" checkbox is checked, but much more complex options are available.


Collapsible Side Panel Control

Question: I am looking for a way to create or implement a collapsible side panel inside of a form. Similar in the way a ToolStripContainer works I would like the same general concept except using panels that I can fill with controls. Does anyone know of a simple way to do this with the provided .Net controls or is this a total custom job. Either way I would appreciate some suggestions.
Answer: There is an example with code here:  http://www.codeproject.com/Articles/8220/Collapsible-Panels-in-VB-NET
Comment: I know this is an old question, but I figured I would answer anyway for the sake of visitors.
Answer: Try this it's in c# but I am sure it can be easily translated
Start a new Project and add a panel.
Dock that panel to the left of the Form.
Add a button to the Panel dock it to the right
Set the Button Text to "<" and Width to 20.
in the button1_Click event add this
<code>    private void button1_Click(object sender, EventArgs e)
    {
        if (button1.Text == ">")
        {
            panel1.Width = 200;
            button1.Text = "<";
        }
        else
        {
            panel1.Width = button1.Width;
            button1.Text = ">";
        }
    }
</code>
What happens here is when the button is clicked the form is shrunk off to the left, leaving only the button visible.  When the button is clicked again, it expands back out.

Collapsible Side Panel Control


using loop variable in ng-class and ng-click attribute

Question: The following code creates a list of seven thumbnails and the active image should have the class active (and thumb).

The images are displayed correctly, but the class active is not applied to the currently selected image, and the images are not changed on click.
That is the controller:
function Gallery($scope) {
    $scope.imgNumber = "1";
    $scope.change = function(imgNumber) {
        $scope.imgNumber = imgNumber;
    }
}

If I unroll the loop and replace no with the current image number everything works as expected.
Why doesn't work the expression in ng-class and ng-click?
Answer: I can't see anything wrong with it. I've tried to emulate it with this jsFiddle: http://jsfiddle.net/63xze/ and it seems to work as expected. Could you edit that jsFiddle to illustrate your issue?
Since I can't post a jsFiddle without code, here's what my jsFiddle looks like:
<!doctype html>

{{no}}

Comment: Thanks, your answer helped me to find the problem and the solution.
Answer: The problem and hence the solution was outside of my example:

The Problem is the
 tag which contains a
 what is simply an illegal nesting!
If I replace p with div everything works as expected.

Answer: Check out the documentation on expressions http://docs.angularjs.org/guide/expression
Conditions are not allowed:

No Control Flow Statements: you cannot do any of the following in angular expression: conditionals, loops, or throw.

The solution is to create a method in your controller. Even for something as simple as equals. It is possible to add this method to the $rootScope if you want to use it in many controllers.

If, on the other hand, you do want to run arbitrary JavaScript code, you should make it a controller method and call the method.
Comment: ngClass allows conditions. Notice he has single curly braces (object) not double curly brances (expression)
Comment: Really? Then the documentation is missleading. http://docs.angularjs.org/api/ng.directive:ngClass The link "expression" leads to the page I linked to above.
Comment: Its a fine point, it is an expression, the expression just resolves to true or false, so there are no flow statements per se.


how can I copy some characters into string in c++

Question: In one part of my code I should get characters one by one. It's easy but my question is how can I add these characters one by one into a string. Note that I don't know how many characters I will get.
It is important that just the characters be copied in string. In the other words, I want to generate words from characters until the character is not equal to ' ' or '\n' .
the wrong code that I wrote is:
 char c;
 string str = NULL;
 cin.get(c);
 while (c != " ")
 {
      str += c;
      cin.get(c);
 }
 cout << str ;

For example, if character c would be 'H' at first and then be 'i',
I want to the string str  to be "Hi" on cout!
Comment: Why `string str = NULL;` and not simply `string str;`? This isn't `char*`
Comment: ok I changed it but the code is wrong too.
Comment: @0bijanmortazavi Please don't accept an answer until you're certain it fits your needs and then I'd encourage you not to change your accepted answer.
Answer: =! should be !=, and the string " " should be a character ' '.
If you want to check for new-line characters as well as space:
while (c != ' ' && c != '\n')

or perhaps
while (!std::isspace(c))

which will read up to any whitespace character.
You should also check for the end of the stream or other problems:
while (cin.get(c) && !std::isspace(c)) {
    str += c;
}

Comment: `str += c` will do that.
Comment: no it's wrong I have a lots of c characters and the lenght of str is not given
Comment: It's in a loop, so it will append a different character (the one you just read from `cin`) to the string each time. You'll end up with all the input characters (until the first space) in the string, like you want.
Answer: If you just want to read until a space or newline:
std::getline( cin, str, ' ' );

Comment: Nope. `std::getline` stops either at the default delimiting character (\n) or the one that you provide, not both. For instance, consider this code and input: http://ideone.com/rMLH5G

The result is expected to be just "Foo"
Answer: c++ stringstreams are also useful when building strings
stringstream ss;
while (cin.get(c) && !std::isspace(c)) {
    ss << c;
}
string s = ss.str();
cout << s;

Answer: The mistake in your code was that you weren't checking for the newline character.
Also, it should have been != instead of =!. The second option will actually behave as c = (!(" ")) in your code. Another mistake is that you should be checking for the blank space character ' ' instead of an empty string " ".
Here is the correct code:
char c;
string str = "";
while (true)
{
     cin.get(c);
     cout << "c is " << c << endl;
         if ((c == ' ') || (c == '\n'))
     break;
     str += c;
}
cout << str << endl ;

Also, if your requirement is that the I/O be stopped the moment a space character is encountered, refer to this question: C - Reading from stdin as characters are typed
All the solutions proposed here will continue to read input until the new line character is entered because until then your input hasn't been processed, but instead stored in a buffer.
Comment: Obijan mortazavi : Sorry, I had done some stupid mistake in my code. I know its unacceptable, but in my defense its 4 am here. Anyway, this code should solve the problem. However, you still need to press enter as the I/O does not stop after a blank space. But the final returned answer just contains data till the first blank space.
Comment: the problem is not while !!!! is how can I copy or add characters one by in a string?
Comment: Obijan mortazavi : the str += c adds a character to the end of string str. In other words, str += c is the same as str = str + c. The get in the loop will keep reading characters one by one.
Answer: If your str starts out empty, this is simple:
string str;

cin >> str; // cin's >> operator already reads until whitespace

cout << str;

Comment: I have to give characters one by one using char variable! ok?
Comment: @0bijanmortazavi I'm not certain why you'd want to do it this way but if that's what you want then [Mike Seymour](http://stackoverflow.com/users/204847/mike-seymour)'s answer is a good one.
Comment: how can i copy or add characters into string? this is my problem now. please help me
Comment: @0bijanmortazavi If you are willing to type the whole line at the prompt and then press enter my code will use `cin`'s `operator>>` to put the first word in `str`. If you need to read in character by character, [Mike Seymour](http://stackoverflow.com/users/204847/mike-seymour)'s use of `string`'s `operator+=` will do the copy.
Answer: If you don't know in advance how many characters it would be, I would declare a std::list, push elements to it and then copy them into a string. This ensures that you don't reallocate the string memory on every addition:
char c;
list<char> buff;
cin.get(c);
while (c != ' ' && c != '\n')
{
    buff.push_back (c);
    cin.get(c);
}
string str (buff.size(), 0);
size_t i = 0;
while (!buff.empty())
{
    str[i] = buff.front();
    buff.pop_front();
    ++i;
}
cout << str ;

Comment: the line "std::list buff;" has an error may be it is for the library. please help me
Comment: What kind of error? Did you `#include ` in the header?
Comment: thank you very much but it has a new error for this line "std::string str (buff.size());" I think this is for size type
Comment: Right, there was an error in the string declaration. I'll fix it.
Comment: please give me a code to copy or add characters one by one into string
Comment: Fixed. The code is now compiling and running as expected: http://ideone.com/Qcnx5W


Can vectors be "more" collinear than others?

Question: Suppose I had vectors $$\mathbf{a} = \begin{bmatrix}1\\1\\0\\0\\0\\0\end{bmatrix} \mathbf{b} = \begin{bmatrix}1\\1\\0\\0\\0\\1\end{bmatrix} \mathbf{c} = \begin{bmatrix}0\\0\\0\\0\\1\\1\end{bmatrix}$$
(The specific numbers in the vectors don't matter, only the axes they exist on). Would it make sense, or be at all correct to say that $\mathbf{b}$ is "more collinear" with $\mathbf{a}$ than with $\mathbf{c}$ because they are on more of the same axes? And if not, is there a way to describe what I'm talking about?
Comment: You can compute the angle between those vectors.
Comment: True, you could say the cosine distance is smaller between more similar vectors, but what is the word for the similarity here? Is it correct to say they're "strongly colinear" or does it not make sense to use the word "colinear" in that way
Comment: I have never heard anything like that, it doesn't really make sense to use the word "collinear" here.
Comment: I would say that in the $a-c$ subspace, $\mathbf b$ is preferentially aligned along $\mathbf a$
Comment: @Andrei that sounds like what I'm looking for. Could you point me to a definition of preferential alignment? Google is no help
Comment: I have this for a physics definition https://dictionary.iucr.org/Preferred_orientation
Answer: You can calculate the angle between the two directions using scalar product. In fact use $$\cos^2\theta=\frac{(\mathbf a\cdot\mathbf b)^2}{|\mathbf a||\mathbf b|}$$
The reason to use $\cos^2$ is to ignore the antiparallel case.


jqgrid creating a hyperlink with an id as the a parameter

Question: I have a simple jqgrid.
colModel: [ { name: 'CatId', index: 'CatId', width: 30, align: 'left' }, ...
What I want to do is turn a column into a hyperlink like this example I find on google:
formatoptions:{baseLinkUrl:'someurl.php', addParam: '&action=edit'}
However I want to put the CatId as the parameter, eg:
formatoptions:{baseLinkUrl:'someurl.php', addParam: '&action=<CatId>'}

I can't seem to find any examples of how to do this, other than possibly just hooking into the loadcomplete event and going through and manually updating every row. Is there a nice way to solve this?
Answer: The URL used by formatter: "showlink" will be constructed using formatoptions which could be baseLinkUrl, showAction, idName and addParam. The formatter "showlink" uses rowid (the id attribute of
 elements of the grid) for constructing the URL. The URL will be built as
baseLinkUrl + showAction + '?' + idName + '=' + rowId + addParam

So the main problem is whether the value of CatId column be used or can be used as the rowid. If you would use key: true option to the definition of CatId column then jqGrid will use the value from CatId as rowid and you could use
formatter: "showlink", formatoptions: { baseLinkUrl: "someurl.php", idName: "action" }

If the value of CatId column can't be used as rowid then I would recommend you to use formatter: "dynamicLink" instead (see jQuery.jqGrid.dynamicLink.js here). I described it in the answer.


Wanting to use an image with text in Html.ActionLink

Question: I am using the following:

@Html.ActionLink("Register",
   "Register",
   "Users",
   null,
   new { title = "Register your ID", rel = "nofollow"
})

What I would like is for the lock image to appear inside of the   so it is clickable and not before it. I already use (and change color on hover) of a background image so its not possible for me to use the background-image property to display the image.
Can anyone think of a way that I can set the image so that it will show before the text and still be clickable. Hopefully I can find a way that still allows me to use the MVC Html.ActionLink.
Comment: You might want to rephrase your question. What do you mean by "appear inside"? Do you mean you want both the image and text to be clickable?
Comment: Sorry if I wasn't clear. Yes I would like the image and text to appear inside the   and both be clickable.
Comment: duplicate of [Image equivalent of ActionLink in ASP.NET MVC](http://stackoverflow.com/questions/210711/image-equivalent-of-actionlink-in-asp-net-mvc)
Answer: Html helpers in ASP.NET MVC should be used when they simplify writing code, not always. Plain html would go way better in your case

     Register

Note that link address is still generated dynamically, using UrlHelper.Action method. This way, you do not lose link dependency to your route configuration. Also, as Nicholas mentioned, image source should be generated via Url.Content helper.
Comment: You should also use
Comment: I think ur ans is better than Mark's ans http://stackoverflow.com/questions/596444/html-actionlink-as-a-button-or-an-image-not-a-link
Answer: You may use something like -
@Html.ActionLink("link Name", "Action Method", "Controller", new { style = "background-image:url('.././Images/imageName.png')" },null)

Answer: @Html.ActionLink("link Name", "Action Method", "Controller",
   new { style = "background-image:url('.././Images/imageName.png')" },
   null)

Comment: Although this code may be help to solve the problem,
providing additional context regarding _why_ and/or _how_ it
answers the question would significantly improve its
long-term value.  Please [edit] your answer to add some
explanation.


Render to 3D Texture with OpenGL on OSX (multi-layer framebuffer attachment)

Question: I have an OpenGL 3.2 CORE context on OSX 10.7.5 set up and trying to render to a 3D texture,
using a layered rendering approach. The geometry shader feature "gl_layer" is supported, but I cannot bind a GL_TEXTURE_3D to my framebuffer attachment. It returns GL_FRAMEBUFFER_UNSUPPORTED.
This is the card and driver version in my MBP:

AMD Radeon HD 6770M 1024 MB - OpenGL 3.2 CORE (ATI-7.32.12)

This feature does not directly relate to a specific extension AFAIK.
Does anybody know how to figure out whether this is unsupported by the driver or hardware?
Thanks so much.
Below the code to reconstruct. I use glfw to set up the context:
// Initialize GLFW
if (!glfwInit())
    throw "Failed to initialize GLFW";

glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 3);
glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 2);
glfwOpenWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwOpenWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);

// Open a window and create its OpenGL context
if (!glfwOpenWindow(720, 480, 8, 8, 8, 8, 24, 8, GLFW_WINDOW))
    throw "Failed to open GLFW window";

//
// ...
//

GLuint framebuffer, texture;
GLenum status;
glGenFramebuffers(1, &framebuffer);
// Set up the FBO with one texture attachment
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, framebuffer);
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_3D, texture);
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexImage3D(GL_TEXTURE_3D, 0, GL_RGBA8, 256, 256, 256, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
glFramebufferTexture(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, texture, 0);
status = glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER);
if (status != GL_FRAMEBUFFER_COMPLETE)
    throw status;
//
// status is GL_FRAMEBUFFER_UNSUPPORTED here !!!
//

glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
glDeleteTextures(1, &texture);
glDeleteFramebuffers(1, &framebuffer);
exit(1);

Answer:
Does anybody know how to figure out whether this is unsupported by the driver or hardware?

It just told you. That's what GL_FRAMEBUFFER_UNSUPPORTED means: it's the driver exercising veto-power over any framebuffer attachments it doesn't like for any reason whatsoever.
There's not much you can do when this happens except to try other things. Perhaps rendering to a 2D array texture.
Comment: Looks like neither TEXTURE_2D_ARRAY nor a cube map works. only a 2D texture. This seems odd, because layered rendering is supported by the geometry shader extension which is part of 3.2 CORE. What would be a layered rendering target left then?
Comment: @FHoenig: Cubemaps. Ultimately, the implementation is allowed to veto anything it doesn't like for arbitrary reasons. These things work on Windows and Linux (granted, that's not exactly helpful for you), so it's not a hardware issue.
Comment: @FHoenig: Nothing. As I said, the implementation *does not have to* let you use anything it doesn't feel like letting you use. That's what `GL_FRAMEBUFFER_UNSUPPORTED` is for. Granted, it's not *supposed* to be used this way, but the OpenGL specification allows it. That being said, are you *certain* that you're getting unsupported and not some other enumerator?
Comment: I get unsupported :-/ OpenCL also doesn't have cl_khr_3d_image_writes on this driver. Time to try windows on this mac.


O que são web workers e como utilizá-los

Question: Através de pesquisas entendi que Web Workers permitem a simultaneidade de processos no JavaScript. Seria como disparar uma thread JavaScript que atualiza a View.
Pode-se considerar que seria a adaptação do padrão MVC ao JavaScript? Gostaria de mais informações e principalmente quais os cuidados no seu uso.
Answer: De fato, um Web Worker é similar a um thread separado do principal. Entretanto, ele é completamente isolado tanto deste quanto do DOM (i.e. da "View"), de modo que a única forma de comunicação entre ele e a thread principal é através do uso de postMessage. Além do DOM, ele também não tem acesso a outras funcionalidades e variáveis/funções/classes globais disponíveis aos scripts comuns.
A principal utilidade de um Web Worker é separar em um thread/processo separado qualquer processamento pesado/demorado que de outra forma bloquearia totalmente a página até que o mesmo estivesse concluído. Um exemplo de uso seria:
script_normal.js
// Cria o web worker
var worker = new Worker('web_worker.js');

// Diz o que fazer quando o web worker enviar uma mensagem
worker.addEventListener('message', function(e) {
    var dados = e.data;
    alert("O resultado é: " + dados.resultado);
});

// Manda uma mensagem pro web worker
worker.postMessage({ cmd:"acharPrimo", n:100 }); // assíncrono - retorna imediatamente

web_worker.js
// Diz o que fazer quando outro thread enviar uma mensagem
addEventListener('message', function(e) {
    var dados = e.data;
    if ( dados.cmd == "acharPrimo" ) {
        var ret = acharPrimo(dados.n); // Chama uma função demorada
        postMessage({ resultado:ret }); // Manda o resultado como mensagem
    }
    // Outras funções, se aplicável
});

function acharPrimo(n) {
    // Acha o n-ésimo primo, construindo um crivo, etc...
}

Ou seja, quando a página inicia o processo demorado, ela não "trava" até que esse processo esteja pronto - você pode continuar utilizando-a, da mesma forma que o faria se tivesse feito uma chamada Ajax pro servidor (exceto que, nesse caso, tudo está acontecendo no próprio browser). Esse processo ocorre em paralelo e, ao terminar, envia os resultados para a página (em um evento também assíncrono) que pode então fazer alguma coisa com ele. Tanto a página quanto o worker podem mandar múltiplas mensagens um pro outro - por exemplo, para exibir ao usuário uma barra de progresso.
Um cuidado que é preciso ter com seu uso é no envio de mensagens: o thread principal e o worker possuem espaço de endereçamento separados (i.e. não compartilham memória). Isso significa que todo dado passado de um para o outro é serializado em uma string antes de ser enviado. No exemplo mostrado, quando se passou:
{ cmd:"acharPrimo", n:100 }

pro worker, não foi um objeto que foi passado, e sim uma string representando esse objeto. No caso, o objeto era pequeno, mas se fosse algo bem grande (tipo um array com vários elementos) a sua cópia de um para o outro - mediante representação em string, ainda por cima - poderia ter um impacto significativo na performance. Há uma alternativa - ainda não amplamente suportada, pelo menos da última vez que eu chequei - que seria o uso de transferables, objetos cuja "propriedade" é transferida de um thread para outro. Ou seja, o mesmo objeto que antes estava em um thread agora passa a estar em outro, tornando-se inacessível ao primeiro, mas sem que ocorra cópia alguma.
Outro cuidado necessário seria lembrar que o web worker em si é single-threaded, ou seja: depois que um processo demorado começou, ele tem de ir até o final antes de outro começar. Ele pode mandar mensagens para o thread principal à vontade, mas a recíproca não é verdadeira: enquanto esse código não terminar de executar, mensagens mandadas ao worker serão enfileiradas até que o mesmo esteja disponível.
Um corolário é que não dá para "matar" o processo mandando uma mensagem de stop para ele - pois essa mensagem só seria recebida depois que o processo já terminou mesmo... Num caso desses, seria preferível que seu worker só executasse uma única iteração do loop por vez, pausando antes de executar a próxima (dando tempo para que as mensagens pendentes fossem processadas). E, é claro, se você possui dois ou mais processamentos a realizar, ou você cria dois workers ou garante que um deles está ocioso antes de reutilizá-lo (um pool de workers é melhor que criar sempre um novo, pois elimina o overhead da criação).
Por fim, convém citar que um WebWorker comum só está acessível ao thread que o criou (seja o principal, ou outro web worker), mas é possível compartilhar um worker com outros através do uso de um SharedWorker. Sua funcionalidade é bastante similar a de um worker comum, mas sua API possui algumas diferenças, em especial na forma de um thread se comunicar com outro.
Comment: @Jota [Na MDN](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/basic_usage) (tabela de compatibilidade no fim da página).
Comment: Claro, conciso e esclarecedor! Obrigado! Só mais uma questão, onde consigo me informar a partir de quais versões os browsers suportam _Web Worker_?
Comment: @Jota Conforme o [caniuse.com](http://caniuse.com/#search=webworker) todos os *browsers* exceto IE9 ou anterior dão suporte. `SharedWorker`, por outro lado, [somente Chrome e Firefox](http://caniuse.com/#feat=sharedworkers). Não tenho informação sobre *transferables*...
Comment: Mais uma vez obrigado pelos esclarecimentos.


MySQL trims value in WHERE

Question: I didn't find a similar question maybe because I don't find the correct words (English is not my first language)
Problem
I have a varchar value that has a blank space at the end: "opt-193-381-markets " and when I do a SELECT with the value without the blank space, it returns the same result. It's like MySQL is trimming the value in the WHERE
Table definition:
mysql> desc message;
+------------+--------------+------+-----+---------+-------+
| Field      | Type         | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+-------+
| FileId     | int(11)      | NO   | PRI | 0       |       |
| MessageKey | varchar(100) | NO   | PRI |         |       |
| NumericKey | tinyint(1)   | NO   |     | 0       |       |
| IsObsolete | tinyint(4)   | YES  | MUL | NULL    |       |
| notes      | text         | YES  |     | NULL    |       |
+------------+--------------+------+-----+---------+-------+

Examples:
mysql> SELECT * FROM message WHERE MessageKey = "opt-193-381-markets";
+--------+----------------------+------------+------------+-------+
| FileId | MessageKey           | NumericKey | IsObsolete | notes |
+--------+----------------------+------------+------------+-------+
|    304 | opt-193-381-markets  |          0 |          1 | NULL  |
|    337 | opt-193-381-markets  |          0 |          1 | NULL  |
+--------+----------------------+------------+------------+-------+

Notice that the MessageKey has the value with the blank space at the end and I just asked for the value without that blank space.
mysql> SELECT * FROM message WHERE MessageKey = "opt-193-381-markets ";
+--------+----------------------+------------+------------+-------+
| FileId | MessageKey           | NumericKey | IsObsolete | notes |
+--------+----------------------+------------+------------+-------+
|    304 | opt-193-381-markets  |          0 |          1 | NULL  |
|    337 | opt-193-381-markets  |          0 |          1 | NULL  |
+--------+----------------------+------------+------------+-------+

Adding one more space
mysql> SELECT * FROM message WHERE MessageKey = "opt-193-381-markets  ";
+--------+----------------------+------------+------------+-------+
| FileId | MessageKey           | NumericKey | IsObsolete | notes |
+--------+----------------------+------------+------------+-------+
|    304 | opt-193-381-markets  |          0 |          1 | NULL  |
|    337 | opt-193-381-markets  |          0 |          1 | NULL  |
+--------+----------------------+------------+------------+-------+

Escaping the spaces
mysql> SELECT * FROM message WHERE MessageKey = "opt-193-381-markets\ \ ";
+--------+----------------------+------------+------------+-------+
| FileId | MessageKey           | NumericKey | IsObsolete | notes |
+--------+----------------------+------------+------------+-------+
|    304 | opt-193-381-markets  |          0 |          1 | NULL  |
|    337 | opt-193-381-markets  |          0 |          1 | NULL  |
+--------+----------------------+------------+------------+-------+

I've also tried with single quotes 'opt-193-381-markets'
Question
Why I cannot search for the exact value of MessageKey?
Thanks
Comment: try to use single qoutes instead of double quotes `'opt-193-381-markets '`
Comment: I've tried it, it's the same
Comment: So... now I will look into that.
Comment: Interesting, had never noticed this before.
Comment: What is the charset of this column / table?
Comment: and what version of MySQL is this?  There are a bunch of articles related to this:  http://stackoverflow.com/questions/12542889/mysql-5-5-losing-trailing-spaces-in-query and http://dev.mysql.com/doc/refman/5.0/en/char.html
Comment: see http://stackoverflow.com/questions/14703349/mysql-disable-auto-trim
Answer: Use the binary comparison operator .
SELECT * FROM message WHERE BINARY(MessageKey) = 'opt-193-381-markets';
Comment: Thank you!, This have worked. In minutes I'll give you the check

MySQL trims value in WHERE


Why does a marathon start need to be near its finish for a record to count

Question: In the answer to a question on the validity or otherwise of a world record, the answer quotes the rule book which says:

"The start and finish points of a course, measured along a theoretical straight line between them, shall not be further apart than 50% of the race distance." [i.e., 13.1 miles (21.1 km) for the ~26.2 mile (~42.2 km) marathon distance]

Why should this be so? I can understand stipulations about ascent or descent between the start and end, but why should the endpoints need to be close together? (It means that the original 26.2 mile course, from Windsor to White City in west London, wouldn't be legal.)
Comment: If you're going to nitpick, be accurate; while the original might have been in Greece, that isn't reasoning behind the 26.2 miles that we run today: http://en.wikipedia.org/wiki/Marathon#Distance
Comment: Just to nitpick, the true actual original marathon wasn't from Windsor to White City, but from Marathon to Athens, hence the name :-)
Comment: Wasn't this a problem with the Rio olympic marathon?
Comment: Responding very late to @Bernhard's comment - the Rio Olympic marathon had both start and finish at the Sambodromo, so it was record-legal, although there may have been earlier, proposed courses which were not. The "classic" Marathon-to-Athens course used in 2004 was not record-legal under this rule.
Answer: Several other traditional marathon courses - notably the Polytechnic Marathon (Windsor to Chiswick) which hosted a few WRs in its time - are also not record-valid under this rule, which is relatively recent.
Ken Young of the Association of Road Race Statisticians has done a lot of work on the effects of wind direction on race times, and has published an overview of his work on the topic.

Some 20 years ago, I worked out a simple model that demonstrated runners could receive a significant tail wind benefit on a course whose start and finish lay more than 30% of the race distance apart.

Young asserts, and I believe he's right, that his work is the basis of the USA's current 30% separation rule. The IAAF rule of 50% separation is more lax, and Young believes still allows for what he considers "unacceptable" benefit. (Young also believes records set by women in races which include men should not be accepted either, but that's another story entirely.)
Comment: While I have no citation for this, for obvious reasons, the rumor is that the IAAF rule allows 50% separation instead of 30% separation because of the lobbying of representatives from several large Japanese marathons which would be record-ineligible under the 30% rule but are OK under the 50% rule. This supposedly also accounts for the IAAF's insistence on women's records coming in separate, not mixed, races.
Answer: Aside from elevation, prevailing wind direction might dictate close proximity of start and finish to ensure a 'fair' race.
Comment: Not that I necessarily doubt you, but do you have a citation for this?
Comment: The basic rules are here: [IAAF COMPETITION RULES 2012-2013](http://www.iaaf.org/mm/Document/06/28/89/62889_PDF_English.pdf): rule 260.28 (approximate page 244). I cannot find documents that explain or argue for the rules...


$\int \frac{1}{48!} (t^{48}) (e^{-t}) \, dt$

Question: What is the integral from 0 to 30 of:
$\int \frac{1}{48!} t^{48} (e^{-t}) \, dt$
I tried integration by parts but it gets more complicated! Is there another simpler way?
Comment: I doubt this has a nice closed form expression.. In any case look up gamma and incomplete gamma function
Answer: Integration by parts results in
$$
\int \frac{t^{48}}{48!}e^{-t}dt
=-\frac{t^{48}}{48!}e^{-t}+\int \frac{t^{47}}{47!}e^{-t}dt
$$
You can continue with the remaining integral in the same way and each time the factorial and the exponent will decrease by one, such that you finally get
$$
\int \frac{t^{48}}{48!}e^{-t}dt
=
-\sum_{k=0}^{48}\frac{t^k}{k!}e^{-t}
=
-e^{-t}\sum_{k=0}^{48}\frac{t^k}{k!}
$$
Comment: It is probably also noteworthy to note that the sum is the initial part of the exponential series, which can be useful when inserting the integration limits.
Answer: Something humorous: Maxima's output.
integrate(t^(48)*%e^(-t)/factorial(48),t);
gives us
((-12413915592536072670862289047373375038521486354677760000000000-12413915592536072670862289047373375038521486354677760000000000*t-
6206957796268036335431144523686687519260743177338880000000000*t^2-2068985932089345445143714841228895839753581059112960000000000*t^3-
517246483022336361285928710307223959938395264778240000000000*t^4-103449296604467272257185742061444791987679052955648000000000*t^5-
17241549434077878709530957010240798664613175492608000000000*t^6-2463078490582554101361565287177256952087596498944000000000*t^7-307884811322819262670195660897157119010949562368000000000*t^8-
34209423480313251407799517877461902112327729152000000000*t^9-3420942348031325140779951787746190211232772915200000000*t^10-310994758911938649161813798886017291930252083200000000*t^11-
25916229909328220763484483240501440994187673600000000*t^12-1993556146871401597191114095423187768783667200000000*t^13-142396867633671542656508149673084840627404800000000*t^14-
9493124508911436177100543311538989375160320000000*t^15-593320281806964761068783956971186835947520000000*t^16-34901193047468515356987291586540402114560000000*t^17-
1938955169303806408721516199252244561920000000*t^18-102050272068621389932711378908012871680000000*t^19-5102513603431069496635568945400643584000000*t^20-
242976838258622356982646140257173504000000*t^21-11044401739028288953756642738962432000000*t^22-480191379957751693641593162563584000000*t^23-20007974164906320568399715106816000000*t^24-
800318966596252822735988604272640000*t^25-30781498715240493182153407856640000*t^26-1140055507971870117857533624320000*t^27-40716268141852504209197629440000*t^28-
1404009246270776007213711360000*t^29-46800308209025866907123712000*t^30-1509687361581479577649152000*t^31-47177730049421236801536000*t^32-1429628183315795054592000*t^33-42047887744582207488000*
t^34-1201368221273777356800*t^35-33371339479827148800*t^36-901928094049382400*t^37-23734949843404800*t^38-608588457523200*t^39-15214711438080*t^40-371090522880*t^41-8835488640*t^42-205476480*t^43-
4669920*t^44-103776*t^45-2256*t^46-48*t^47-t^48)*%e^(-t))/(12413915592536072670862289047373375038521486354677760000000000
Answer: For a crude bound:
$$\int_0^{30} \frac{1}{48!} t^{48} (e^{-t}) \, dt = \mathbb{P}(X\le 30)$$
where $X$ is a $\Gamma(49,1)$ random variable, i.e. a sum of $49$ i.i.d. standard exponential random variables. Thus, for $\beta>0$:
$$\mathbb{P}(X\le 30)=\mathbb{P}(e^{-\beta X}\ge e^{-30\beta})\le \frac{\mathbb{E}[e^{-\beta X}]}{e^{-30\beta}}=\frac{e^{30\beta}}{(1+\beta)^{49}}$$
and optimising over $\beta$, we choose $\beta=\beta^{opt}=\dfrac{19}{30}$ to obtain the numerical bound
$$\int_0^{30} \frac{1}{48!} t^{48} (e^{-t}) \, dt \le e^{19}\left(\frac{30}{49}\right)^{49}=0.00647\cdots$$
One could also obtain an approximate bound by appealing to the Central Limit Theorem in a similar way, ultimately looking at $\mathbb{P}\left(Z\le -\dfrac{19}{7}\right)\approx 0.0033\cdots$.
Checking with WolframAlpha, though, both bounds are actually very crude - the actual value is $0.00089\cdots$.


"limpar" texto escrito no input A e reescreve-lo no input B utilizando jquery

Question: Tenho um < input type="text" id="A" >, gostaria que ao digitar um texto qualquer nesse input, ele fosse reescrito no input B, porém antes do texto ser reescrito, gostaria que ele passa-se por uma "limpeza". Essa limpeza é pra tirar os caracteres especiais do texto, e pra substituir o "espaços" por "-".
Atualmente já faço essa "limpeza" com php, só que não é algo dinâmico. Assim nem sempre o texto limpo fica da maneira que eu quero! Exemplo disso é a seguinte situação!
Antes:
"Esse é um TEXTO que ééu quero LIMpar! Verá ele limpo em Seguida!"

Depois
"esse-e-um-texto-que-eeu-quero-limpar--vera-ele-limpo-em-seguida-"

Agora com essa reescritura do texto eu vou poder controlar melhor o resultado final! Assim caso eu não goste eu vou poder editar o texto final antes mesmo de cadastrar no banco de dados.
O código php que uso pra limpar esse texto é:
$ltag = strtolower(preg_replace('{\W}', ' ', preg_replace('{ +}', ' ', strtr(utf8_decode(html_entity_decode($tag)), utf8_decode('ÀÁÃÂÉÊÍÓÕÔÚÜÇÑàáãâéêíóõôúüçñ'), 'AAAAEEIOOOUUCNaaaaeeiooouucn'))));

Answer: Para fazer um replaceAll em todos os "espaços" precisa implementar o restante é coisa simples, fiz um exemplo:

String.prototype.replaceAll = function(de, para){
        var str = this;
        var pos = str.indexOf(de);
        while (pos > -1){
                    str = str.replace(de, para);
                    pos = str.indexOf(de);
            }
        return (str);
    };

    var teste ={};

    teste.limpar=function(){
        $('#A').keyup(function(){
            var aux = new String( $(this).val() );
            aux = aux.replaceAll(" ","-").toLowerCase();
            aux = teste.replaceSpecialChars(aux);
            $("#B").val(aux);
        });
    };

/**
 * Array de objectos de qual caracter deve substituir seu par com acentos
 */
var specialChars = [
 {val:"a",let:"áàãâä"},
 {val:"e",let:"éèêë"},
 {val:"i",let:"íìîï"},
 {val:"o",let:"óòõôö"},
 {val:"u",let:"úùûü"},
 {val:"c",let:"ç"},
 {val:"A",let:"ÁÀÃÂÄ"},
 {val:"E",let:"ÉÈÊË"},
 {val:"I",let:"ÍÌÎÏ"},
 {val:"O",let:"ÓÒÕÔÖ"},
 {val:"U",let:"ÚÙÛÜ"},
 {val:"C",let:"Ç"},
 {val:"",let:"?!()"}
];

/**
 * Função para substituir caractesres especiais.
 * @param {str} string
 * @return String
 */
teste.replaceSpecialChars= function (str) {
 var $spaceSymbol = '-';
 var regex;
 var returnString = str;
 for (var i = 0; i < specialChars.length; i++) {
  regex = new RegExp("["+specialChars[i].let+"]", "g");
  returnString = returnString.replace(regex, specialChars[i].val);
  regex = null;
 }
 return returnString.replace(/\s/g,$spaceSymbol);
};

    teste.limpar();

<input type="text" id="A" />
<input type="text" id="B" />

A parte da expressão regular segue o link http://snipplr.com/view/15532/replace-de-caracteres-especiais-por-seu-equivalente-sem-acento/
Testado com Chrome em:
http://fiddle.jshell.net/sneeps_ninja/wxse2p7u/1/


Active backup or restore

Question: Hoje ao fazer um insert em uma tabela foi apresentada a mensagem: The transaction log for database "nome do banco" is full due to "ACTIVE BACKUP OR RESTORE".
Qual o motivo dessa mensagem?
Answer: Por padrão, no SQL Server, todo banco de dados possui um arquivo com extensão .ldf que armazena os logs de transações. Dependendo das configurações ele pode chegar ao seu tamanho limite e começar a apresentar a mensagem que você recebeu.
Uma das formas de contornar esta situação é definir uma estratégia de autocrescimento (autogrowth) de acordo com o espaço disponível no hd. Para isto, no Management Studio, basta clicar com o botão direito do mouse sobre o banco e selecionar a opção Propriedades. No menu do lado esquerdo escolha a opção Files (Arquivos) e localize o arquivo de LOG do seu banco. Na coluna Autogrowth/Maxsize você define sua estratégia.
Se não quiser/puder mexer nestas configurações você pode executar o comando shrink de acordo com o artigo abaixo:
https://www.mssqltips.com/sqlservertutorial/3311/how-to-shrink-the-transaction-log/
Em ambos os casos vai precisar ficar sempre de olho no espaço que o arquivo está ocupando.

Active backup or restore


Allow users to configure notified email addresses

Question: I want my users to be able to subscribe new commit notifications. Subscriptions should be per gitolite repository, and the user shouldn't have to contact me every time they want to add a subscription or project. Is there a hook which allows that?
Answer: Why not use a post-receive hook to send commit messages to a mailing list (per-project, managed by majordomo or similiar) and let people subscribe/unsubscribe to the list?
Then all you have to do is create the per-project mailing lists once and let the software deal with the rest.
Comment: This sounds prone to breakage. But more importantly, my users can also setup their own repositories, so I'd have to allow/teach them to create a mailing list as well.
Comment: There are plenty of majordomo front-ends that let users create their own mailing lists (or you could make your users use a repo-creating script that also creates the mailing list). Routing the commit messages to a battle-proven mailing list system is how every major source-hosting project I'm aware of (and every decently managed company) solves this problem, and I'd wager it's less prone to breakage than trying to home-grow your own system. Mailing lists are a solved problem, you're almost certainly better off using that solution [trying to reinvent the wheel](http://vimeo.com/2997888).


Centos 5.6 switching/migration from apache to lighttpd

Question: I'm currently running Apache 2 with PHP 5.1.6 running as mod_php on a Centos 5.6 box.
I use .htaccess for mostly redirection.
I already have latest APC running apc.so.
I also have MySQL, etc.
Until recently I've been reading things like;

Running php as fastcgi benefits on high traffic sites.
Using squid as a proxy for static content.

All this time my confusion is increasing, until I finally landed on lighttpd which seems to encompass all those optimizations.
Problem is, there is no up to date article covering the complete migration from Apache to lighttpd.
Secondly, I've read a little on lighttpd being used as a proxy for Apache serving static content.
Which is better? Complete migration or start from scratch using lighttpd or simply setting httpd as a proxy.
Comment: Subjective opinion: NGINX is better than lighttpd. Also you should probably provide more details, are you using any kind of config/management tool (CPanel, Webmin etc.). Are you running custom applications or standard FOSS software (Wordpress, Joomla PHPBB etc.).
Comment: What problem are you trying to fix? Low memory? High CPU? Complex config you want simplified?  Or just a general interest in moving from Apache to lighttpd?  Why you want to migrate makes a difference, also it depends how many sites you've got, etc.
Comment: ok sorry, low memory was a big factor. anyway. ive installed nginx as a front end for apache serving static content. it was very easi and straight forward http://jamescacchione.net/featured-articles/experiments-with-varnish-nginx-apache-on-centos
Answer: There's no up-to-date article on switching from apache to lighttpd because, for all practical purposes, lighttpd has been replaced by nginx.  Lighttpd was great for it's day, but I'm afraid it hasn't got anything going for it now.
I'd make a complete migration to nginx; I've not had a need for an Apache-specific feature in years.


Space occurred in loop after IDEA formatting

Question: how to avoid space after val in my sample below?
for (Exception val : list) {
         ...
}

after IDEA formatting i wanna have
for (Exception val: list) {
         ...
}

Thanks
Comment: what is the language??
Comment: now i'm writing java
Answer: Settings => Code Style => (Choose your language) => Choose Spaces Tab => Set your desired places to add spaces
Comment: yes, i know about it dialog, but can't find checkbox i need((
Comment: Before property name-value separator ':'
Comment: what IDEA edition are you use? i'm on Community Edition
Comment: @Dragos there is different value. There is an example `x = y >= 0 ? arr[y] : -1;` which is not `enhanced for loop`.