Proof for the arithmetic progression

Question: So I was going through a few olympiad questions, and here is a question I found

Now, I found the three terms of the progression in terms of a and b, and arrived at $a^2$+ 2 b + 1 = 0.
However, I'm stuck at this point. What do I do now?
Comment: @smcc - $b$ may be irrational :\
Comment: Yes I just realized my mistake!
Comment: b = -5/2 is a obviously counterexample.
Comment: @ZackNi - It won't satisfy the integral A.P. condition
Comment: Sorry my mistake.
Comment: What do the crooked parantheses denote?
Answer: As you wrote, we have
$$P(0)^2-P(-1)^2=P(1)^2-P(0)^2\implies 2b=-a^2-1\tag1$$
Since $P(-1)^2,P(0)^2=b^2$ and $P(1)^2$ are integers, we have that
$$4b^2-1=(2b)^2-1=(-a^2-1)^2-1=a^2(a^2+2)\in\mathbb Z\tag2$$
and that
$$P(-1)^2-P(1)^2=2a(a^2-1)\in\mathbb Z\tag3$$
Now let $b^2=m$ where $m$ is a positive integer($m=0$ leads that $a^2=-1$). Then,
$$b^2=\left(\frac{-a^2-1}{2}\right)^2=m\implies 4m=(a^2+1)^2\implies 2\sqrt m=a^2+1$$
Also, from $(3)$, there exists an integer $n$ such that
$$2a(a^2-1)=n\implies 2a(2\sqrt m-2)=n\implies a=\frac{n}{4\sqrt m-4}$$
where we may assume that $\sqrt m\not=1$ ($\sqrt m=1$ leads that $a^2=1,b=-1$).
Therefore,
$$(a^2=)\ 2\sqrt m-1=\left(\frac{n}{4\sqrt m-4}\right)^2\implies (2\sqrt m-1)(\sqrt m-1)^2=\frac{n^2}{16}\in\mathbb R$$
$$(2\sqrt m-1)(m-2\sqrt m+1)\in\mathbb R\implies 2m\sqrt m+2\sqrt m+2\sqrt m\in\mathbb R\implies \sqrt m\in\mathbb R$$
It follows from this that $a,b$ are rational numbers.
So, we can set $b=-\frac pq$ where $p,q$ are coprime positive integers, and we have that $b^2=\frac{p^2}{q^2}\in\mathbb Z$ from which $q=1$ follows. Therefore, $b$ is an integer.
It follows from this that $a^2$ is an integer. Similarly, we get that $a$ is an integer.
Comment: The problem statement doesn't make it clear whether $P(-1)^2$ is the 1st member of the arithmetic progression, $P(0)^2$ is the 2nd, $P(1)^2$ is the 3rd. Unless the crooked parentheses denote that (I don't know what they denote).
Comment: @user236182: Well, to be honest, I have never considered the other possibilities. But now I agree that the problem statement is unclear. So, I have to say that my answer supposes that they denote $P(-1)^2$ is the 1st, etc. Anyway, thank you for pointing that out.

Proof for the arithmetic progression


Positive integers less than 1000 without repeated digits

Question: How many integers from 1-999 do not have any repeated digits?
The answer is explained in this link, but why is the last set 9*9*8? Why not 9*9*9?
Answer: In the link, they claim that $9\cdot 9\cdot 8$ gives the number of integers from $100$ to $999$ with no repeated digits. You have three digits $d_1d_2d_3$ to work with. Begin with the first digit $d_1$: it can be any number in $\{1, \ldots, 9\}$. When choosing the second digit $d_2$ you must avoid repeating $d_1$, but you can now use $0$, so you select from $\{0, \ldots, 9\} - \{d_1\}$. So while the first two factors of $9 \cdot 9 \cdot 8$ are the same, there is an interesting difference between picking $d_1$ and picking $d_2$. Similarly, the the last digit must come from $\{0, \ldots, 9\} - \{d_1, d_2\}$, and this set has size $8$.
Comment: Thank you so much, Dylan! I had been attempting this problem for at least an hour!
Comment: @user754950 No problem. Hope it makes sense now.


AJAX works based on geographical location?

Question: I have a site that calls AJAX. It works at my office, where I made it (that is, on many people's computers, on different systems and browsers, not just mine) and it worked from one outside computer (a friend of mine who lives about 10 min from the office). The AJAX fails, however, on every other outside computer. If I try it at home, or another friend of mine tries it at his home, it doesn't work (we live far away from the office). It is a very simple AJAX call using jquery.
$(destination).load(url);

I checked it with Firebug Console and found this
the AJAX call is listed as
GET (url) 200 OK

when it works AND when it doesn't work, except that when it doesn't work, its in red and there is an 'X' icon in between the OK and the 152ms(or however long it took).
Params tab - are the same whether it works or not
Headers tab - when it works, the 'request headers' section shows:
X-Requested-With    XMLHttpRequest
Cookie  PHPSESSID=*******

But when it doesn't work, these lines are absent but instead there is a line for 'Origin' (which just has the main sites URL in it).
Response/HTML tabs - are empty when it doesn't work.
As I said, I've tested for browsers, computers, Mac, Pc etc and it all works at the office, but not anywhere far away. Any help is greatly appreciated.
UPDATE
I created a test page to separate out the code. The test page worked briefly, then stopped working (which bewilders me). So I now think that my code has an error, but that the error is somehow overlooked by browsers when it happens to work (the original still works in the office, while the test doesn't).
The test page should have 'Worked!' pop up when the 'test' link is clicked. Here is the code:
<?php
$call = $_GET['call'];
echo $call;
if($call == 'yes') //check for call
{
    echo 'Worked!';
    exit();
}
?>

<!DOCTYPE html><title>Test</title>

test

Comment: What is the URL you are trying to load ? (if it's not a secret)
Comment: @florian The page I'm loading works fine, even from home (they work if I go to them directly instead of doing the AJAX call). It's a simple listing of some database info. I'm certain the problem has to do with there not being an XMLHttpRequest in the request headers, but I have no idea why that's the case.
Comment: Does `url` look like `http://www.example.com/page`, `/page`, or `page`?
Comment: @icktoofay it is an absolute url. I just put up some code in an edit
Comment: @icktoofay Thanks! Your question led me to the answer. See my solution below!
Answer: Here is what you can do to try to target the "bug".

(if possible) test the Ajax request aside of your project. Make an independant (freshly downloaded jquery.js file) page in your project that loads the expected content and see if it works. In this case the "bug" is relative to your project itself.
I figured out that I don't have an XmlHttpRequest in the header when the URL doesn't match the host I'm loading the URL from. (for instance trying to load the google.com page). Check that you're not doing crossdomain requests. (I don't think so since it works at your friend's)

[The extreme one]

I don't know what kind of project it is (public or not) but I already worked on a project where the database access was restricted to certain IP addresses. IP addresses in a given area are similar, so maybe it works fine at your friend's because he lives close to your office and not at your home because IP addresses are too different.

I'm not sure that any of the propositions above could be the solution to your problem but maybe it could help.
Comment: I put up a test page with a dumbed-down version of my code. Thanks for the suggestions. I'll check that IP address thing out.
Answer: The problem is with using the absolute path for the url. It matters to the code whether or not 'www' is in the address bar. So, if you go to the page with 'www' in the address bar, but it isn't in the code url (or vice-versa), it won't work.
The reason it didn't work at some peoples computers is because when they accessed the page, those people didn't put in the 'www' and their address bar didn't match the code url.
Thanks to icktoofay for putting me on the right path to figure this out.


how to use date(), timezone() and timestamp() command in codeigniter

Question: Good day. may i ask how the timestamp() and timezone() command is working? i tried to put a date (8-13-1996),  but the date that inserted in the database is (1970-01-01). is it the timestamp() or the timezone() command?
here is my code..
$bday = $this->input->post('mm')+" "+$this->input->post('dd')+" "+$this->input->post('yy');
$new_member_insert_data = array(

    'birthday' =>date("Y-m-d", strtotime($bday))

);
$insert = $this->db->insert('users', $new_member_insert_data);

Answer: It seems strtotime cannot convert the string into time.It gets false.
date("Y-m-d",false)==1970-01-01
date("Y-m-d",0)==1970-01-01

you should better check if it can covert the string into time
 $bday = $this->input->post('mm')+" "+$this->input->post('dd')+" "+$this->input->post('yy');
 $time=strtotime($bday);
 if($time!==false)//insert it if $bday can convert into time
 {
   $new_member_insert_data = array(

     'birthday' =>date("Y-m-d", $time)

   );
   $insert = $this->db->insert('users', $new_member_insert_data);
}

Also you converting the string wrong way.You used +it should be .
Use this way  $bday=$this->input->post('mm')."-".$this->input->post('dd')."-".$this->input->post('yy');


Existe função "main()" em Python?

Question: Em algumas linguagens, como em C, temos a função main() que normalmente é o ponto de entrada padrão do programa. Existe algo similar em Python?
Answer: Não há uma função main() em Python, pelo menos não da forma explícita. O que temos é o '__main__' que é o nome do escopo do código executado em top-level, sendo que é definido em __name__ o nome do modulo. O '__main__' é definido quando o script é executado do terminal interativo ou chamado pelo interpretador da linguagem.
Você pode obter um "comportamento parecido" com o main() da seguinte forma:
if __name__ == '__main__':
   main()

Isso vai impedir que o conteúdo do script seja executado quando for importado:
import meuscript

Assim tudo que estiver no bloco do if não vai ser executado na importação, a não ser que você faça:
from meuscript import main
main()

e chame a função main() diretamente.
Veja na documentação.
Answer: Não existe no python uma função main() como no C. Contudo existe uma variável nativa chamada __name__ (com dois underlines antes e depois).
No python temos os módulos que podem se executados de forma indepedente ou importados em outro script. Com a variável __name__ é possível sabermos se o script está sendo executado por meio de uma importação ou de forma direta.
Se o script estiver sendo executado por meio de uma importação, então a variável __name__ recebe o nome do módulo importado. Agora se o script estiver sendo executado diretamente, por exemplo com o comando python script.py, então a variável __name__ recebe o valor __main__.
Nesse link tem informações mais detalhadas: https://blog.alura.com.br/o-que-significa-if-name-main-no-python/
Answer: Python é uma linguagem de script então ela já começa existir. De uma certa forma existe, mas não da mesma forma que C. Não existe formalmente, o código que é encontrado que não está dentro de uma função é tido como uma função global, a entrada padrão é o script que você mandar executar, dali ele vai executando.
Coloquei no GitHub para referência futura.
Answer: Falando em ponto de entrada da aplicação, Python não define uma função para tal.

Os programas são interpretados de cima para baixo, como é comum em linguagens de script. 3

Veja: https://stackoverflow.com/questions/36794098/designing-a-program-entry-point-in-python

Existe função "main()" em Python?


serve a static file in nginx based on domain extension.ltd?

Question: I was wondering and already did some extensive searches on how to serve a static file based on the domain.LTD extension.
Nginx.conf:
error_page 502 /maintenance.html;
location = /maintenance.html { root /srv/books/current/app/views/layouts/; }

What I want is to serve a localised maintenance page based on the extension of the domain for that current request. Is this possible somehow using regex or any nginx directives?
Answer: How about something like..
error_page 502 /maintenance.html;
location = /maintenance.html {
  if ($http_host ~* "\.([^\.]+)$") {
    set $tld $1;
    rewrite ^ /maint/$tld.html last;
  }
}

location /maint/ {
  root /path/to/somewhere/maint/com.html;
}

That should make it load com.html for the maint page for example.com, etc.
Comment: testing this now, you removed the root variable? how to add that back in. I assume like rewrite ^ /my/root/path/to/maintenance_$tld.html last; to load /my/root/path/to/maintenance_com.html?
Comment: @Rubytastic This would have a different location block handle where the root configuration resides, since nothing but `/maintenance.html` matches this location block.  See edit.


Laravel regex validation for price OR empty

Question: I am trying to make a regex for price OR empty.
I have the price part (Dutch uses comma instead of point) which actualy works
<code>/^\d+(,\d{1,2})?$/
</code>
The regex above validates ok on the value 21,99
Now I try to add the empty part so the field can be... just empty ^$
<code>/(^$|^\d+(,\d{1,2})?$)/
</code>
But Laravel starts to complain as soon as I change the regex:
"Method [validate^\d+(,\d{1,2})?$)/] does not exist."
Works ok:
<code>$rules = [
    'price' => 'regex:/^\d+(,\d{1,2})?$/'
];
</code>
Laravel says no...:
<code>$rules = [
    'price' => 'regex:/(^$|^\d+(,\d{1,2})?$)/'
];
</code>
Kenken9990 answer - Laravel doesn't break anymore but an empty value is still wrong:
<code>$rules = [
    'price' => 'regex:/^(\d+(,\d{1,2})?)?$/'
];
</code>
Comment: Can you add a valid & invalid patterns, from which regex need to validate.
Comment: In php are you able to use a regex like a lambda function? I didn't think you could.
Comment: @emsimpson92 I am not a programmer,  a Lambda?
Comment: My apologies, I meant an anonymous function. `=>` is C# syntax for exactly that. It looks like it has [a different meaning](https://stackoverflow.com/questions/14037290/what-does-this-mean-in-php-or) in PHP. Your problem is with the `=>`
Comment: @emsimpson92 In PHP you create an array like that. Example 1 works, example 2 fails. It's just the regex I think, or Laravel..., oh and now I know what you mean with Lamba, something with passing a value to a function or something?
Comment: Yes, but you're assigning a keyvaluepair with the key `price` and value `your regex`. the regex is not your value, just the pattern you want to run the value through
Answer: is this work ?
<code>$rules = [
    'price' => 'nullable|regex:/^(\d+(,\d{1,2})?)?$/'
];
</code>
Comment: @poashoas Add `'nullable'`
Comment: submit a empty input will change to null, means set to nullable and no need regex for the empty part
Comment: You are my hero, I 54ck at regex
Comment: what a bummer, it doesn;t break anymore but still it's says an empty value is not OK, but it should
Comment: @WiktorStribiżew that should be an answer, not just a comment
Comment: sorry for i test it on pure php code preg_match(), and i forgot empty input will change to null, @WiktorStribiżew that should be an answer
Comment: @poashoas If you read documentations, you would have found the answer earlier than somebody else that googled it for you.
Comment: @revo and you just got here to tell me how dissapointed you are in me?
Comment: @poashoas Not really. The point is reading manuals prevents people from being surprised mistakenly.
Comment: @revo sorry for my angry response, but it makes somebody feel stupid. Stackoverflow is a place to ask silly questions too. And yes, I do read documentation but it didn't popped my mind, I was to busy with the regex.
Comment: @poashoas I didn't call your knowledge into question.
Answer: <code>|</code> is also the separator for multiple validation rules.
For example the following is valid:
<code> $rules = [ "price" => "nullable|numeric|between:0,99" ];
</code>
To use it regex you need to switch to using an array:
<code>$rules = [
    'price' => [ 'regex:/(^$|^\d+(,\d{1,2})?$)/' ]
];
</code>
This is also pointed out in the documentation:

Note: When using the regex / not_regex patterns, it may be necessary to specify rules in an array instead of using pipe delimiters, especially if the regular expression contains a pipe character.

Incidentally the original rule might also do what you want and can also be written as:
<code>$rules [
     'price' => [ 'nullable', 'numeric', 'between:0,99' ]
]
</code>


Distribution of time intervals in a Poisson process

Question: I am studying computational neuroscience, particularly the modeling of neuronal spikes. Abstractly, we may think of a spike plainly as some event that either occurs or fails to occur in time. It has been established that the probability that $n$ events (spikes) occur in a trial of time $T$ follows a Poisson distribution with
$$
P_{T}(N = n) = \frac{(rT)^{n}}{n!}\exp(-rT)
$$
Here, $r$ is the firing rate of the neuron (or the constant rate at which events occur in time). It was also established early in the book that $r\Delta t$ is the probability that any spike occurs at some time interval $[t, t + \Delta t]$. As a note, the equation above in the book is numbered $1.29$ - I clarify this for it is referenced in the fragment I need help with.
This is all the context required to understand the following fragment of the book, with which I need some help.

I can fully comprehend the paragraph above up to equation $1.31$. What I don't understand is what immediately follows it. Namely, that the PDF of interspike intervals is equation $1.31$ without the factor $\Delta t$, or in other words, that the probability that an interval $[t + \tau, t + \tau + \Delta t]$ is an interspike interval is
$$
r\exp(-r\tau)
$$
I did observe that such expression is the derivative with respect to $\Delta t$ of equation $1.31$. However, equation $1.31$ is not a CDF, and hence its derivative is not the PDF we are interested in. What am I missing?
Answer: The probability density $f_X$ of a random variable $X$ can be defined via the following limit
$$
f_X(x) = \lim_{\Delta \downarrow 0} \frac{P(x < X \leq x+\Delta)}{\Delta}.
$$
for a.e. $x$. This results from the Lebesgue differentiation theorem. Now in your case the random variable is $t_{i+1} - t_{i}$ and the $\Delta$ is your $\Delta t$. The density at $\tau$ is then $r \exp(-r\tau)$ since the $\Delta t$ cancels out.


utilizar ref em uma lista sem v-for vue.js

Question: Olá, tenho uma lista simples na qual não utilizo o v-for. Gostaria de saber se é possível identificar o item da lista através do #ref no vue.js;
Normalmente identifico meus componentes com name e Id, porém estou utilizando um componente de terceiros o qual não tenho acesso a essas propriedades.
Preciso pegar o índice do item da lista e gostaria de saber como fazer isso pelo ref.
Grata
Answer: Sim, é possível.
Quando não utilizando o v-for, a ref se torna uma variável comum, podendo ser resgatada com this.$refs.suaref.
Utilizando o ref no componente com o v-for o nome dado na referência se
torna uma array de componentes, utilizando this.$refs.suaref[indice] é possível trabalhar com o componente referenciado.
Obs:
Mesmo com componentes de terceiros é possível utilizar id e name(não o do .vue, o do componente mesmo) sobre eles, todas as propriedades podem ser utilizadas, e ela será adicionada no elemento raiz do componente, mas geralmente o id que você define sobrepõe o do componente, mas raramente quem faz um componente utiliza o id.


CONCAT() and DATE_FORMAT() gives different result in mysql for date range

Question: i am having trouble, when i use CONCAT('2017-01-15', ' 00:00:00') it gives different result than when i use DATE_FORMAT('2017-01-15', ' %Y-%m-%d 00:00:00') in MySQL for date range .. any idea please?
for example my query is
SELECT SUM(payments) as pays
FROM   table
WHERE  employee_id = 25
AND    `date` >= DATE_FORMAT('2017-05-16', '%Y-%m-%d 00:00:00')
AND    `date` <= DATE_FORMAT('2017-05-31', '%Y-%m-%d 23:59:59')
GROUP BY employee_id
ORDER BY id DESC

and with CONCAT
SELECT SUM(payments) as pays
FROM   table
WHERE  employee_id = 25
AND    `date` >= CONCAT('2017-05-16', ' 00:00:00')
AND    `date` <= CONCAT('2017-05-31', ' 23:59:59')
GROUP BY employee_id
ORDER BY id DESC

Both gives different results ..
Comment: See https://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for-what-seems-to-me-to-be-a-very-simple-sql-query
Comment: is 'date' a text field?
Comment: no date is DATETIME field
Comment: Different timezones maybe? Maybe you're passing values from your app which uses a different timezone than your MySQL server, and when the server creates a datetime with date_format, it's in the MySQL server's timezone? You should compare (and possibly provide here) the output of your concat and date_format functions.
Comment: no its not timezone issue i am pretty sure about it.. its something else .. script and mysql both are on same server using same timezone
Answer: Thanks for the responses guyz, actually i had issue in 23:23:59 :) it had to be 23:59:59 :) i didn't notice it somehow ..
Thanks - problem solved
Answer: I just noticed you have the leading space in the format string I copy-pasted. Double check your actual queries for this.
[Disregard below]
It may be some strange casting issue, it appears that DATE_FORMAT (in the server I was testing on) includes a leading space.
This is the query I used to track down this strangeness if you're interested:
SELECT @t0 := '2017-01-15' AS t0, @tN := '2018-01-15' AS tN
, @df0 := DATE_FORMAT(@t0, ' %Y-%m-%d 00:00:00') AS df0, @dfN := DATE_FORMAT(@tN, ' %Y-%m-%d 00:00:00') AS dfN
, @ct0 := CONCAT(@t0, ' 00:00:00') AS ct0, @ctN := CONCAT(@tN, ' 23:59:59') AS ctN
, @df0 = @ct0 AS eq0, @dfN = @ctN AS eqN
, CAST(@ct0 AS DATETIME) = CAST(@df0 AS DATETIME) AS castsEqual0
, @ct0 = CAST(@df0 AS DATETIME) AS castDF0Equal
, CAST(@ct0 AS DATETIME) = @df0 AS castCT0Equal
, @n := CAST(now() AS DATETIME) AS n
, @n > @ct0 AS `n>ct0`, @n > @df0 AS `n>df0`
, @n < @ctN AS `n<ctN`, @n < @dfN AS `n<dfN`
, @n < CAST(@dfN AS DATETIME) AS `n<castDFN`
, CAST(@n AS CHAR) < @dfN AS `castN<dfN`
, LENGTH(CAST(@n AS CHAR)), LENGTH(@dfN)
, CONCAT('[', @dfN, ']')
;

Comment: leading space where ?
Comment: In the format string. `' %Y-%m-%d 00:00:00'` should be `'%Y-%m-%d 00:00:00'`. It looks correct in your examples, but the initial version you gave in your question has it.
Comment: i am grouping by date actually, i think date is doing some issue


Convert variant date (FLOAT) to datetime

Question: I have a table that contains FLOAT field from datetime. When I convert this values to datetime, there is a two days difference between converted date with correct date. For example:

But in this site date convert is correct!!!

In this post, explains why this happens, but what is the solution in SQL Server?
Comment: You need to use the explicit type cast with the correct "zero" date: `select DATEADD(day, 45099, CONVERT(date, '18991230'))`.
Comment: Just subtract two days' worth from the float when doing conversions?
Comment: You can use the ```SELECT DATEDIFF(DAY,'18991230',CURRENT_TIMESTAMP)``` to do the opposite
Comment: At a guess this originally came from a badly converted Excel sheet
Comment: @Charlieface Unfortunately no; this is SQL Server code: ```select cast(getdate() as Int)```
Comment: Well I get 45097 for the same date https://dbfiddle.uk/5UHQdtu1
Comment: @Charlieface These values are added from the attendance device in the table
Answer: You need to construct the datetime value from the correct "zero" date:
SELECT DATEADD(day, 45099, CONVERT(date, '18991230'))

Your current statement uses implicit data type conversion and adds number of days to the default datetime value 1900-01-01.


How to fail the Azure pipeline if any errors are reported in the task

Question: Pipeline is not failing even though the application errors are reported in one of the task. For that i have used failonstderr: true in the pipeline and pipeline detects the errors and start failing. But the problem is failing the pipeline for warnings also. But i am looking for the pipeline should fail when errors are reportedenter image description here not on warnings. Is there any alternate solution?
Comment: You could inject a fail action on your build script for errors. for example using powershell you could add `exit 1` in order to fail your pipeline based on a condition. This way you can skip warnings and exit only on errors
Comment: could you share the yaml task please ?
Comment: Unfortunately i cant able to share the yaml  pipeline script. If  I use exit 1 in my yaml script the task/stage automatically will fail irrespective of the result.
Answer: You could set the control option of each task by disabling Continue on error and running this task Only when all previous tasks have succeeded. Then, if any errors are reported in the task, the pipeline will fail. Please refer to Task control options for more information.

As for YAML pipeline, please make sure you have added continueOnError: false to you task. Alternatively, make sure you haven't added condition: expression to each task. Then, it defaults to Only when all previous task have succeeded.
Comment: I have tried this one. The problem is  the pipeline is successfully executing all the tasks/stages even though the output is not expected/ with errors. I  need to fail the pipeline when the errors are reported in the task. The task/stage should fail and should not proceed to next task/stage
Comment: Hi @sr123, have you enable this setting for each task? Whether you are using Classic or YAML pipeline? Please share your pipeline definition and a screenshot of the pipeline run log.
Comment: Hi @Suki Ji-MSFT. Unfortunately i cant able to share my script. Thanks for the suggestions. Currently i am using yaml Pipelines. Is there any alternate solution?
Comment: Hi @sr123, I have edit the answer, please check if you have set any condition in YAML. Besides, when running the pipeline, are the jobs running one by one in order or disorder? Is the failed task is the one which run last?


Is there any way to determine areas of intersection of n circles?

Question: Is there any algorithm or an image analysis method ( like point process) that can be used to find areas of intersection of n circles?
Comment: do you just want the area (a number) or some way of representing the intersection itself (a shape)
Comment: @Tim my goal is to find the areas' borders
Comment: I don't know if there's a named one. It's certainly possible. I can have a go at coding something. What language are you using?
Comment: @Tim thank you very much. I don't use a specific language , I still think about a theoretical analysis and work, if you want to do some coding I would be happy to collaborate.
Answer: First look at a simple case. Suppose that circle $A$ has radius $r_a$ and centre $(0,0)$ and circle $B$ has centre $(0,R)$ and radius $r_b$. Assume further that $r_a>r_b$. The intersection of the two circles is

Empty if $r_a + r_b < R$
circle $A$ if $r_a - r_b > R$
Interesting if $r_a - r_b < R < r_a + r_b$

In the interesting case the boundary of the intersection is made up of two arcs, one from circle $A$ and one from circle $B$. Let's find the arc from circle $A$.
There are two points where the boundaries of the circles intersect one point at $(\ell, h)$ and the other at $(\ell, -h)$ By Pythagoras we have $\ell^2 + h^2 = {r_a}^2$ Similarly $$\begin{align}{r_b}^2  &= h^2 + (R-\ell)^2\\ &= h^2 + R^2 +\ell^2 - 2R\ell \\ &= R^2 + r_a^2  - 2 R\ell \\ \Rightarrow \ell &= \frac{R^2 +{r_a}^2-{r_b}^2}{2R}\end{align}$$
So the arc from circle $A$ is the arc between angles $(-\theta,\theta)$ where $r_a\sin\theta = \ell$.
I've only used lengths in the calculation of $\theta$ so for any two circles you can find the angle $\alpha$ between the two centres and apply the same calculation to get an arc between $(\alpha-\theta, \alpha + \theta)$
Now let's introduce circle $C$ part of my arc will be outside circle $C$ and won't contribute to the boundary, and part of my arc will be inside circle $C$. This part of the arc is the boundary between $A\cap B \cap C$ and $B\cap C \cap A^\complement$ that is

It is the contribution to the boundary of circle $A$ to the intersection $A\cap B\cap C$
It is part of the contribution of circle $A$ to the intersection $A\cap C$

So the contribution to the boundary of circle $A$ is the intersection of the two arcs between circles $A$ and $B$ and circles $A$ and $C$ as calculated above.
Now you can reason inductively and argue that the contribution to the boundary of circle $A$ to the intersection of $N$ circles is the intersection of the pairwise arcs calculated as above.
This gives you a basic algorithm which runs in $\mathcal O(N^2)$ where $N$ is the number of circles.

Choose a circle $A$ and for each $B\neq A$ calculate an arc $(\theta_{a,b}^0, \theta_{a,b}^1)$ as above.
Calculate the intersection of all the arcs. If the intersection is empty discard circle $A$ and begin again with a new circle.
If not the intersection will be in the form $(\theta_{a,x}^0, \theta_{a,y}^1)$ for two circles $X$ and $Y$.
Perform steps 1 and 2 for circle $Y$ this must give you something in the form $(\theta_{y,a}^0, \theta_{y,z}^1)$
Repeat with circle $Z$ and keep going until you get back to circle $A$.

This will give you a list of arcs and if you keep track of the endpoints of your arcs a polygonal path. The intersection is then the union of the segments formed by the arcs and the inside of the polygonal path.
Comment: I have a few questions : 1) By R you mean the X axis ?,2)Here you assume the circles are not homogenous , what if they are homogenous , have the same radius?
Comment: 1)  $R$ is the distance between the centres of the two circles. For the first stage I assumed both circles have centres on the x axis, one at $(0,0)$ and one at $(0,R)$.  2) I should have written $r_a\geq r_B$. If $r_a = r_b = r$ then we get $\ell = \frac R 2$ and $\sin \theta = \frac R{2 r}$.


$\lim_{x \to 3} x^2$, Clearly the value is 9, How can we be sure of this in an infinite precision system such as a number line(i.e infinite zoom)?

Question: My question is: on a number line which has infinite precision i.e can be infinitely zoomed, so now as we approach 3(x->3), we approach closer to 9, here if we approach infinitesimally close we get infinitesimally close to 9, but in a system as this which has infinite precision even infinitesimal values can't be appropriated to zero(such as 0.00000...1) and if I try to understand this with epsilon and delta definition a chain of reasoning is formed(Apologies if I have incomplete Information) where I get to a small interval, I get a small enough value to approximate but then the graph can be zoomed again and this continues again and again and we never actually get 9 then how and why can we write 9 in a case such as a graph on a phone or computer which can be infinitely zoomed?
In other words how does the limit win against the infinite zooming?
Answer: The definition of a limit is:
$$\forall \epsilon > 0: \exists \delta>0:|f(x)-L|<\epsilon \quad\forall x \in (x_0-\delta, x_0+\delta)$$
then $\displaystyle \lim_{x\mathop\to x_0}f(x) = L$.
This definition allows for any $\epsilon$, no matter how small it is. If the graph is zoomed again, we find a new $\delta$ satisfying this, and we can always find that $\delta$ provided that the limit exists.


Que microframework devo usar?

Question: Atualmente estou estou estudando o Fat-Free Framework porem estou me debatendo com muitos problemas algumas funções simplesmente não funcionam como deveriam, e outras se comportam de maneira bem diferente do que é documentada, como ainda estou somente estudando o framework fico com receito de usa-lo em uma aplicação real.
Com isso fico na duvida, como o F3 está se tornando complicado qual alternativa de framework eu poderia usar ?
Comment: cara, muda a pergunta para algo mais direto: "Que microframework devo usar?" ou algo assim.
Comment: @Daniel Obrigado, fiquei na na duvida de como titular a minha questão.
Comment: Essa é uma pergunta muito particular, tem *N* frameworks disponíveis. Zend e Cake eu acho um elefante branco, Kohana e Laravel nunca usei além do *demo*, mas parece-me que são os que tem a menor curva de aprendizado.
Answer: Então, só numa busca rapidassa no Google por php microframework você já acha de cara as seguintes:
Lumen, que é baseada no Laravel
Silex, que usa componentes do Symfony
Slim
Flight
Nenhum desses eu usei. Já usei o FatFree que me atendeu, e já usei o Epiphany pra um projeto que estava rodando um servidor capenga IIS que rodava uma versão meio antiga do PHP (e nem usei ele todo, só umas poucas coisas).
Na real, microframeworks servem pra você não usar tudo, construir bastante coisa no braço, seja por que você quer aprender ou por que o projeto é muito pequeno e uma framework robusta vai atrapalhar mais do que ajudar. Onde trabalhei, usavam a Zend e eram bem felizes, mas quando fui tentar aprender fiquei coçando a cabeça e desisti.
Comment: Agora que percebi, em um outro comentário você me indicou o F3, mas em testes das funções ele deu muitos erros, eu estou vendo sobre esse Laravel achei interessante e a documentação enorme. agora me resta saber a diferença entre o Lumen e o Laravel puro.

Que microframework devo usar?


Como capturar a extensão de um arquivo no R

Question: Estou com dificuldade para capturar a extensão dos arquivos importados.
Gostaria de extrair a extensão do arquivo e armazenar em uma variável.
arquivo <- "dados/Inscritos.xls"
extensao <- ?

Answer: Esta função utiliza basename para ficar com os nomes de ficheiros sem os diretórios. Depois verifica se os nomes de ficheiros têm um ponto ou não. Finalmente, extrai só o que está entre o último ponto "." e o fim dos nomes de ficheiros.
extensao <- function(x){
  x <- basename(x)
  y <- character(length(x))
  i <- grep("\\.", x)
  y[i] <- sub("^.*\\.(.*$)", "\\1", x[i])
  y
}

extensao(arquivo)
#[1] "xls"

fls <- list.files(full.names = TRUE)
fls <- fls[!file.info(fls)$isdir]
extensao(fls)

Answer: Você pode utilizar regex através do pacote stringr

O parênteses define a parte da extração do texto
\w+ define que é uma palavra
$ define que é no final da string

    library(stringr)
    arquivo <- "dados/Inscritos.xls"
    extensao <- str_extract(arquivo, '(\\w+)$')

Answer: Com o R base, dá pra usar a função strsplit:
arquivo <- "dados/Inscritos.xls"
extensao <- unlist(strsplit(arquivo, split = "\\."))[2]

Como o resultado de strsplit é uma lista, é necessário transformá-la em vetor através do comando unlist e aí retirar o segundo elemento desse vetor.
Comment: Pensei nesta solução, mas é sempre possível ter mais de um ponto nos arquivos.
Comment: Verdade. Não me dei conta disso.


Facebook: open graph checkins in on one map

Question: I have Open Graph feature in my app. I have to maintain the total check-ins in my Facebook account. And have to show the all checked-in places in one map. Foursquare app used this in their app. But i don't know, how to implement like that.
They have used two ways of showing in aggregation,
First one is,

And the second one is,

So, I have to do the both like Foursquare app. Please help me in this.
Thanks in advance!!!
Answer: They are most likely using the map custom aggregation feature.  Check out the documentation here: https://developers.facebook.com/docs/opengraph/guides/collections/#styles.  You'll need to attach location data to your actions in order for this aggregation to work.  You can learn more about the Place property at https://developers.facebook.com/docs/opengraph/guides/tagging/#places


Como redimensionar imagens antes do upload usando c# asp.net

Question: estou aprendendo .net mvc 4 e gostaria de saber se existe alguma biblioteca boa e simples, para redimensionar imagens antes de fazer o upload, pesquisei no google e só achei funções complexas com cálculos de redimensionamento feitos na mão. Como isso é algo bem comum, acredito que exista alguma biblioteca pronta e funcional para essa tarefa. Alguém conhece alguma?
Answer: descobri que a biblioteca System.Web.Helpers possui uma classe chamada WebImage. Nela é possível fazer o redimensionamento da imagem e salvar o upload. Só precisei de uma lógica pra achar a altura correta, pois ela não permite que se passe apenas largura ou altura como parametro, então, o código ficou assim:
int width = 800;
int height = (int)Math.Round(((width * 1.0) / image.Width) * image.Height);
image.Resize(width, height);
image.Save(path + fileName);

Fonte: https://stackoverflow.com/questions/14613325/resize-image-width-in-c-sharp-but-not-the-height
Answer: Acredito que isso possa resolver:
http://www.codeproject.com/Articles/23011/Simple-Image-Resizing-Library
e um componente que faz o redimensionamento das imagens:
http://imageresizing.net/docs/basics
Comment: a combinação dessa biblioteca com o componente é exatamente o que eu queria. Obrigado Thiago!!
Comment: Thiago, essa biblioteca funciona com a imagem em formato "FileUpload" do WebForms, preciso de uma biblioteca que funcione com "HttpPostedFileBase" do MVC. Sabe se tem como adaptar ou só com outra biblioteca mesmo?
Comment: pra você fazer funcionar com HttpPostedFileBase seria só adicionar as referências System.Web, System.Web.HttpPostedFileBase e System.Web.HttpPostedFileWrapper, acredito que dê certo.


Reviewing/voting tag synonyms

Question: Recently I proposed two tag synonyms. These two proposals are currently still pending and with 0 votes.
Is anyone ever looking at these proposals?
Is the SE system actually notifying users with sufficient privileges clear enough? Or is it lacking here?
Comment: Aparently the wish to have notifications was already specified since Nov '13: http://meta.stackexchange.com/questions/204244/improving-tag-synonyms
Answer: It seems only moderators can see/accept them, and it should be listed in their tools
https://magento.stackexchange.com/help/privileges/create-tags
We have only 3 Moderators currently: https://magento.stackexchange.com/users?tab=moderators
Answer: You have to have at least 10 votes or something on a tag to suggest and vote. I have at least for bundle-product <-> bundle suggestion not enough rep on the tags :(
Is there a link I can check the recommendations?

Is anyone ever looking at these proposals?

No, only suggestion on my own.

Is the SE system actually notifying users with sufficient privileges clear enough? Or is it lacking here?

No clue, I don't think so :)

Reviewing/voting tag synonyms


Why is Salsa music counted in 8 if it is in 4/4 time?

Question: The wikipedia page shows salsa notated in 4/4 time and the clave (which marks the rhythm) is written as 16th notes:
1 ee and aa 2 ee and aa 3 ee and aa 4 ee and aa
but most Salsa teachers seem to count it in 8 or two groups of 4 like this not using 16th notes at all but rather as 8th notes.
1 and 2 and 3 and 4 and 5 and 6 and 7 and 8
or
1 and 2 and 3 and 4 and 1 and 2 and 3 and 4
Comment: Dancers almost always count in eight beat phrases without particular regard to the notated musical meter.
Answer: Dancers count by steps rather than by measures, and salsa typically features eight steps per phrase (two measures of 4/4 time). See this similar question on Quora for details:

[In] each 4/4 measure, a dancer steps three times, either left/right/left or right/left/right. That means you need another measure to get back to the same foot. For that reason, it makes a lot of sense to count 2 measures. Mostly salsa dance patterns span 2, sometimes 4, measures.
Comment: Thank you. However, It isn't only dancers. Musicians that teach salsa also divide the "clave" over 2 measures instead of over one measure. The Wikipedia page for "Salsa music" shows it in one measure only using 16th notes.
Answer: The shortest answer is: it isn't by musicians. There are 4 beats per clave. Dancers count in 8 because it's easier to count 'one two three four' than 'one and two and'.


Como fazer um container flex ter a largura dos divs internos?

Question: Boa tarde, estou criando um layout com height:100% onde tenho 2 grupos, e dentro de cada grupo alinho as DIVs verticalmente e se alguma DIV não couber no height máximo ou houver resize da página, ele vai pra outra coluna, como no exemplo:
https://jsfiddle.net/ErickV/xqkujqv8/
Observe que o 2º grupo está sobrepondo a 2º coluna na frente do 1º grupo.
Gostaria que o 2º grupo inicie depois (à direita) da última coluna do 1º grupo. Tem algo errado ou que poderia ser ajustado no CSS?
Fiz uns 'ajustes técnicos' via JavaScript pegando a distância da última div contida no 1º grupo e setei um left no 2º grupo, e se tivesse um 3º grupo, eu repetia esse processo entre o 2º e 3º e assim sucessivamente. Achei muita gambiarra.
Comment: A propriedade `columns` do css não adianta? http://tableless.com.br/css3-columns/
Comment: Acredito que não, fui no exemplo no jsfiddle e apliquei 2 propriedades informadas em seu link mas não surtiu efeito, realizei outros testes junto com as propriedades mas não tive resultado, poderia testar no exemplo para ver se sua dica funciona e postar a solução? talvez fiz algo errado
Answer: ErickV , fiz alguns teste utilizando o código que você disponibilizou e só consegui setando um valor para a largura(width) do grupo 1, em resumo a quando a segunda coluna do grupo 1 é criada a largura não se ajusta aos novos itens, e assim a o grupo 2 sobrepõe a nova coluna criada.
Creio que ao invés de ajustar o left do grupo 2, você pode setar um novo valor para a largura do grupo 1.
Explicando de uma forma mais clara, Atribui o valor de 250px para o grupo um direto no css para a propriedade width.
#group1 {width:250px;}

Utilizei o ID para que só o grupo 1 tenha essa nova largura, porém, acredito que essa forma só é interessante quando você consegue identificar a quantidade de colunas que um grupo tem.
Pois assim você conseguira fazer o calculo e setar um novo valor pro width através do .css() do jquery.
OBS:  o valor de 250 , seria o calculo (122+3)*2 = 250.
122px de largura + 3 de margin, vezes a quantidade de coluna, neste caso duas !
Answer: #container-de-caixas {
    display: table;
    width: 1158px;
}
#caixa-1 {
    width: 578px;
}
#caixa-2 {
    width: 386px;
}
#caixa-3 {
    width: 194px;
}
#caixa-1, #caixa-2, #caixa-3 {
    min-height: 210px;
    padding-bottom: 20px;
    display: table-cell;
    height: auto;
    overflow: hidden;
}

o container deve ter display:table
As caixas dentro devem ser: display:table-cell
Não use float.
Answer: Olá @ErickV!
Acho que apenas adicionando este código com JQuery, seu problema é resolvido! Basicamente o que ele faz é calcular a distância do último filho e calcular a nova largura do seu grupo quando o documento carrega ou quando a janela é redimensionada.
$(window).on('resize',function() {
    $('.tile-grid').each(function( index ) {
         var lastChild = $(this).children().last();
         var newWidth = lastChild.position().left + $(this).position().left + lastChild.outerWidth(true);
         $(this).width(newWidth);
    })
});
$(document).ready(function() {
    $(window).trigger('resize');
});

Segue abaixo um exemplo com o seu próprio código:

$(window).on('resize',function() {
 $('.tile-grid').each(function( index ) {
   var lastChild = $(this).children().last();
   var newWidth = lastChild.position().left + $(this).position().left + lastChild.outerWidth(true);
   $(this).width(newWidth);
 })
});

$(document).ready(function() {
    $(window).trigger('resize');
});
html,
body {
  margin: 0;
  padding: 0px
}

* {
  height: 100%;
}

.tile-container {
  display: block;
}

.tile-group {
  height: 100%;
  display: inline-block;
  margin-left: 3px;
  position: relative;
}

.tile-group .title {
  color: #626262;
  font-size: 24px;
  font-weight: 400;
  position: absolute;
  left: 4px;
}

.tile-grid {
  margin-top: 46px;
  height: calc(100% - 46px);
  position: relative;
  border: 0px solid black;
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  align-content: flex-start;
}

.tile-item {
  width: 122px;
  height: 122px;
  position: relative;
  display: block;
  float: left;
  margin: 3px;
  box-shadow: inset 0 0 1px #FFFFCC;
  cursor: pointer;
  overflow: hidden;
}

#group1 .tile-item {
  background-color: red;
}

#group2 .tile-item {
  background-color: blue;
}

    Grupo 1

        Test

        Test

        Test

        Test

        Test

        Test

    Grupo 2

        Test

        Test


Integer overflow in boolean expressions

Question: I have the following c++ code:
#include <iostream>

using namespace std;

int main()
{
    long long int currentDt = 467510400*1000000;
    long long int addedDt = 467510400*1000000;
    if(currentDt-addedDt >= 0 && currentDt-addedDt <= 30*24*3600*1000000)
    {
                cout << "1" << endl;
                cout << currentDt-addedDt << endl;

    }
    if(currentDt-addedDt > 30*24*3600*1000000 && currentDt-addedDt <= 60*24*3600*1000000)
    {
                cout << "2" << endl;
                cout << currentDt-addedDt << endl;

    }
    if(currentDt-addedDt > 60*24*3600*1000000 && currentDt-addedDt <= 90*24*3600*1000000)
    {
                cout << "3" << endl;
                cout << currentDt-addedDt << endl;

    }

   return 0;
}

Firstly, I get a warning for integer overflow, which strikes me as odd because the number 467510400*1000000 falls well within the range of a long long int, does it not? Secondly, I get the following output:
1
0
3
0

If in both cases currentDt-addedDt evaluates to 0, how could the third if statement possibly evaluate to true?
Comment: What happens if you use `467510400ll * 1000000ll` etc? Maybe the compiler is multiplying them as `int`s.
Comment: `long long int`, yes, but math on all of those constants is likely being performed as `int`
Answer: 467510400*1000000 is within the range of long long, but it's not within the range of int. Since both literals are of type int, the type of the product is also of type int - and that will overflow. Just because you're assigning the result to a long long doesn't change the value that gets assigned. For the same reason that in:
double d = 1 / 2;

d will hold 0.0 and not 0.5.
You need to explicitly cast one of the literals to be of a larger integral type. For example:
long long int addedDt = 467510400LL * 1000000;

Comment: This makes sense. I would also have to do the same to the literals in the if statements themselves too, right? @Barry
Comment: @Danzo Why not store them in `const long long` variables and use those instead?
Answer:    long long int currentDt = 467510400ll*1000000ll;
   long long int addedDt = 467510400ll*1000000ll;

Note the two lowercase letter "l"s following the digits. These make your constants long long. C++ normally interpret strings of digits in source as plain ints.
Answer: The problem you are having is that all of your integer literals are int.  When you multiply them they overflow giving you the unexpected behavior.  To correct this you can make them long long literals using 467510400ll * 1000000ll
Answer: It because
60*24*3600*1000000 evaluates to -25526272

use
60LL*24LL*3600LL*1000000LL

instead (note the 'LL' suffix)
Comment: It doesn't have to evaluate to that.
Comment: Signed integer overflow is undefined
Comment: Also 64-bit `int` compilers are possible.
Comment: @NeilKirk it does in VS2012 debugger
Comment: @NeilKirk, true, but the standard default integer type (without suffix specifiers) in C++ is `int` not `int64`. So literal computation of as posted will evaluate using `int` thus the overflow
Comment: The standard allows `int` to be 64-bits, in which case this `int` calculation will not overflow.
Comment: @NeilKirk, true. So it depends on the compiler doesn't it? And probably whether you're compiling for 32 or 64 bit processors.
Comment: Yes it depends on the compiler what it evaluates to. The processor doesn't matter. Many compilers still use 32-bit `int` even for 64-bit targets.
Comment: @NeilKirk, the processor bitness only matters as the **target** of compilation. Hence the `sizeof(int)` will be different and thus overflow or not constant expressions. Hence it's always better to use the correct suffix when doing constant expressions.
Answer: You have tagged this with C++.
My minimal change to your code would use the c++ static_cast to promote at least one of the literal numbers (of any overflow generating expression) to an int64_t (found in include file cstdint).
Example:
//          0         true
if(currentDt-addedDt  >= 0

&&   // true because vvvv

//          0        true
   currentDt-addedDt <= 30*24*3600*static_cast<int64_t>(1000000))
//                                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

(for test 1, the result of the if clause is true.
 for test 2 and 3 is false)
Upon finding the static_cast, the compiler promotes the 3 other integers (in the clause) to int64_t, and thus generates no warnings about overflow.
Yes, it adds a lot of chars for being, in some sense, 'minimal'.
Comment: And I do not object to LL suffix, but perhaps these literal constants are used elsewhere, and do not need to be bigger than they are declared.

Integer overflow in boolean expressions


Redirect to front page after emptying the shopping cart (ubercart)

Question: How can I redirect to the front page after emptying the cart. I am making a commerce site using the Ubercart module, but it is not redirecting to the front page after the cart is empty.
Comment: You could try changing the submit property on a form_alter?
Comment: Have you tried with rules?
Answer: You can use drupal_goto function.
drupal_goto('<front>');


How to implement 128-bit linear feedback shift register with byte element array in C

Question: I have an array as follows,
unsigned char A[16]
I am using this array to represent a 128-bit hardware register. Now I want to implement a linear feedback shift register (LFSR, Fibonacci implementation) using this long register. The polynomials (or tap) which connect to the feedback xnor gate of this LFSR are [128, 29, 27, 2, 1].
The implementation of a 16-bit LFSR (taps at [16, 14, 13, 11]) can be obtained from Wikipedia as the following.
  unsigned short lfsr = 0xACE1u;
  unsigned bit;

  unsigned rand()
  {
    bit  = ((lfsr >> 0) ^ (lfsr >> 2) ^ (lfsr >> 3) ^ (lfsr >> 5) ) & 1;
    return lfsr =  (lfsr >> 1) | (bit << 15);
  }

In my case, however, I need to shift bits from one byte element to another, e.g. the msb or A[0] need to be shift to the lsb of A1. What is minimum coding to do this shift?
Thank you!
Answer: To calculate the bit to shift in you don't need to shift the whole array every time since you are only interested in one bit (note the & 1 at the end of the bit = line from Wikipedia).
The right shift amounts are:
128 - 128 =   0   => byte  0 bit 0
128 -  29 =  99   => byte 12 bit 3
128 -  27 = 101   => byte 12 bit 5
128 -   2 = 126   => byte 15 bit 6
128 -   1 = 127   => byte 15 bit 7

So,
bit = ((A[0] >> 0)
    ^  (A[12] >> 3)
    ^  (A[12] >> 5)
    ^  (A[15] >> 6)
    ^  (A[15) >> 7)) & 1;

Now, you really need to shift in the bit:
A[0] = (A[0] >> 1) | (A[1] << 7);
A[1] = (A[1] >> 1) | (A[2] << 7);
// and so on, until
A[14] = (A[14] >> 1) | (A[15] << 7);
A[15] = (A[15] >> 1) | (bit << 7);

You can make this a bit more efficient by using uint32_t or uint64_t instead of unsigned chars (depending on your processor word size), but the principle is the same.
Comment: I am the same structure in my mind. I think there is probably not much to simply in the code...


custom display of taxonomy list in views

Question: I'm using a "Content:All Taxonomy Fields" field in a View.  Works great, but-
Can I change the display of taxonomy field lists without custom code?  The vocabulary has an image field I've added...I'd love to show the image instead of the name when listed.
Thanks!
Comment: Why not just use a Taxonomy based view instead of Content based?
Answer: If I understand well your question, you'd like to add the image associated to a term in your view ?
If so, in the view go to advanced (right sidebar) => Relationships. choose "Content: Taxonomy terms on node", then in "add fiels" you should be able to add any field of your terms, like name, description or image...
To Avoid duplicate output, go to "advanced => Query settings" and check "Distinct".
In case you have duplicate output anyway, you can try this other solution :
Add a content-> Nid field (Exclude from display).
Add a global php field. In output code, write something inspired from that, with your own details.
<?php
$q = "SELECT tid, filename FROM `taxonomy_term_data` INNER JOIN `field_data_field_tags` ";
$q.= "ON `taxonomy_term_data`.tid = `field_data_field_tags`.field_tags_tid ";
$q.= "INNER JOIN `field_data_field_img` ON `taxonomy_term_data`.tid = `field_data_field_img`.entity_id";
$q.= "INNER JOIN `file_managed` ON `file_managed`.fid = `field_data_field_img`.field_img_fid ";
$q.= "WHERE `entity_id` = ".$row -> nid;
$m = db_query($q);
while ($s = $m -> fetchObject()) {
  $img = "path_to_img_folder". $s -> filename;
  $tid = $s -> tid;
  echo "".$img."";
}
?>

You'll have then all your taxonomy images displayed in the same row. You may use the style settings to wrap the output with some classes. You'll have also to go to "advanced => Query settings" and check "Distinct". Hope it helps.
Comment: I can do that!  The problem I run in to is if I have multiple matching taxonomy terms, I ultimately get duplicate search results.  In order to avoid the dupes, I have to use "Content: All Taxonomy Fields", instead of associating the actual field I want.
Comment: @user23493 I edited the answer about how to avoid duplicate output. Could you confirm it was useful ?
Comment: Unfortunately, that doesn't work at the moment. (and is documented to not work when multiple taxonomy nodes match).
Comment: Are you using Aggregation?  Thanks!
Comment: You're right, there are some duplicate output. An alternative may be to use a global Php field to display your images. I edited the answer


Extension of $\mathbb{C}$

Question:
I want to prove that $\mathbb{C} \subset \mathbb{k}$ and $\dim_{\mathbb{C}}\mathbb{k} \leq \aleph_{0} \implies \mathbb{C = k}$($\mathbb{k}$ - field).

If $\mathbb{k} \ni e, e^2,\dots,e^n$ are linearly dependent then $\mathbb{C}(e) = \mathbb{C}$ (since the minimal polynomial of $e$ have degree $1$). So now we can consider $\mathbb{k}$ with basis without elements such as $e$ linearly dependent with its powers or powers of another basis elements. So now we have countable basis such as for any basis element $e$ span of its powers has dimension $\aleph_0 \implies$ his potency equal $\aleph_1$.
It sounds terrible and I'm afraid that this is not true.
Can u please indicate my mistakes, but not tell me a solution.
Comment: How is k defined?
Comment: I don't understand why i can't write $= \aleph_0$;(
Comment: and $\dim_{\mathbb{C}}\mathbb{Q}$ is not defined(and Donald Duck is not field)
Comment: @GeorgesElencwajg From a logical point of view you're right (and I removed my comment). But I find such a formulation very poor.
Comment: But why? I don't understand what's wrong?
;(
Comment: @user2715119 The formulation with $=\aleph_0$ is "logically correct", but it could have "$\implies$ the earth is flat" as the thing to prove. In short, the exercise would be better formulated as "Prove that if $k$ is a field extension of $\mathbb{C}$, then its dimension over $\mathbb{C}$ is more than countable". Hint: if $k$ is a proper extension, then it is transcendental, so it contains a copy of $\mathbb{C}(X)$ where $X$ is an indeterminate.
Comment: Dear @egreg, I'm sorry you removed your comment: mine was just meant as a benevolent joke. I find your point that there is no field of denumerable dimension over $\mathbb C$ quite noteworthy: please restore it (I have removed my previous comment and will soon remove the present one).
Answer: The statement you want to prove can be reformulated, perhaps more clearly, as follows:

Let $\mathbb{k}$ be an extension field of $\mathbb{C}$; if $\mathbb{k}$ is a proper extension, then $\dim_{\mathbb{C}}\mathbb{k}>\aleph_0$.

The hint is to observe that

no proper extension of $\mathbb{C}$ can be algebraic, because $\mathbb{C}$ is algebraically closed;
a transcendental extension of $\mathbb{C}$ contains a subfield isomorphic to $\mathbb{C}(X)$ (field of rational functions on the indeterminate $X$).

So it's sufficient to prove that
$$
\dim_{\mathbb{C}}\mathbb{C}(X)>\aleph_0
$$
by finding an uncountable set of rational functions such that no finite subset is linearly dependent over $\mathbb{C}$. Try your hand with
$$
\left\{\frac{1}{X-c}:c\in\mathbb{C}\right\}
$$
that is suggested by partial fraction decompositions.

Note. Your original statement can be rewritten as

If $\mathbb{k}$ is an extension field of $\mathbb{C}$ and $\dim_{\mathbb{C}}\mathbb{k}=\aleph_0$ then $\mathbb{k}=\mathbb{C}$.

I commented (wrongly) that this is false and was corrected by Georges Elencwajg. Indeed, this is a statement of the form "if $A$ then $B$", where $A$ is false (because we're able to prove the statement above). As part of my comment I suggested to change $=\aleph_0$ into $\le\aleph_0$.
I find that the original formulation is, at the least, misleading.

Extension of $\mathbb{C}$


How do I calculate change in number of coins?

Question: "Given an amount of change less than one dollar, find the coins required to make up this amount. Your program should find the minimum number of coins. For example, if the change was $0.56, you would need 2 quarters, 1 nickel and 1 penny for a total of 4 coins. Hint:  Use integer division and remainder."
I have to write code for this on java for a school assignment. I am not allowed to use if statements, how do I do this?
Comment: Kandiah, can you make a list of which coins you are allowed to use ? Most people here are not familiar with American money, and it seems like you have restrictions on which you can use, as your example doesn't show the minimum number of coins required to get 0.56$.
Comment: Stack Overflow is a question-and-answer site, not a homework-writing service.  We are not going to do your homework for you.  [An open letter to students with homework problems](https://softwareengineering.meta.stackexchange.com/questions/6166/open-letter-to-students-with-homework-problems)
Comment: If all you're concerned about is not being able to use an if block, `if (cond) { block }` is equivalent to `for (;cond;) { block; break; }` or `while (cond) { block; break; }`.
Comment: [Why is "Can someone help me?" not an actual question?](https://meta.stackoverflow.com/q/284236/3788176)
Comment: Your instructor is incorrect. 1 [half dollar](https://en.wikipedia.org/wiki/Half_dollar_(United_States_coin)), 1 nickel and 1 penny use three coins. Also acceptable should be 1 half dollar, and 2 [three cent nickels](https://en.wikipedia.org/wiki/Three-cent_nickel). 3 coins is less than 4.
Comment: I'm voting to close this question as off-topic because [**"Questions asking for *homework help* must include a summary of the work you've done so far to solve the problem, and a description of the difficulty you are having solving it."**](https://stackoverflow.com/help/on-topic).
Answer: Like the hint says, use integer division and remainder. Java has the % (modulus) operator to calculate the remainder.
Assuming the change is an int defined in cents (so 99 cents, not 0.99 dollar), you could do something like this:

int coins = change/25 + change%25/10 + ... ;
Comment: Please don't encourage these "do my homework" questions by answering them.  Thank you.
Comment: I have not provided the complete answer to the assignment, OP still has to understand modulus and integer division to finish it.


Passing the user selection value from one activity to another

Question: I am making a small calculation game.
on the main screen there would be a RadioGroup
o Easy o Medium o difficult
Button Continue
then after the user selects this and presses continue then on next page another radio group
o Addition o Subtraction
Button Start
Now I want to display questions depending on the selection of radio buttons from there 2 activities.
How can I do that, for a single radio group I can use changeListener...But here I have to consider values from 2 radio groups simultaneously.
So how to do that. I tried my best to explain this using example and representation too.
Thanks
Comment: Pass the values between screens by adding the value as an extra to the Intent you use to launch it.  The new activity can then read the value from the intent.
Comment: Thanks for the valuable reply...It worked :)
Answer: Use a bundle with Intent extras to pass data between activities.
Intent i = new Intent(getContext(), SecondActivity.class);
Bundle b = new Bundle();
b.putExtra("key", value);
i.putExtras(b);
startActivity(i);

http://developer.android.com/reference/android/content/Intent.html#putExtras(android.os.Bundle)
and in your SecondActivity
getIntent().getStringExtra("key");

http://developer.android.com/reference/android/content/Intent.html#getStringExtra(java.lang.String)
Comment: there are also methods getLongExtra(), getSerializableExtra(), etc.
Comment: Thanks for the answer and useful links, It worked and still I will go over through the links..
Answer: For the apps that I've been involved with I've been using a application object to store state variables that need to be visible in more than one activity.  The application object gets created before any activity objects, and is the last thing to be destroyed when the application is closed, so it's a good place to store state variables.  You're allowed one application object per app, and the class type needs to be declared in the manifest.  It sounds like your difficulty variable and your add/subtract are state variables, so I'd suggest you go down this path.
Comment: Why this instead of Intent data?
Comment: As I said, I think this is good for state variables.  If I've misunderstood and the variables in question are not global state variables for the app then I agree that `Intent` is best.
Answer: You may also want to use the SharedPreferences if you want to save the value longer the current instance.
See for more details.
http://developer.android.com/guide/topics/data/data-storage.html#pref


Problema ao mostrar/ocultar divs ao subir site

Question: Olá, estou utilizando JQuery para mostrar/ocultar as divs. Quando abro a página local as divs funcionam normalmente (abrem e escondem), porém ao subir a página para a web (realizar a hospedagem), as divs não funcionam mais.
Já olhei no inspecionar e não está mostrando nenhum erro. Minha dúvida é, o que pode estar ocasionando esse erro? E se possível, me ajudarem com uma forma mais funcional de fazer isso? Desde já agradeço.
É esse o código que estou usando:
<!DOCTYPE html>

 <meta charset = "utf-8">
 <meta name = "viewport" content = "width:device-width, initial-scale=1">
 <title>Mostrar/Ocultar</title>
 <link rel="stylesheet" href="lib/bootstrap/css/bootstrap.min.css">
 <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

 <link rel="stylesheet" type="text/css" href="lib/css/estilo.css">

Solicitar Carimbo

Portaria

Carimbo

Auditorio

CSS:
#carimbo
{
text-align: center;
width: 100%;
margin: 0 auto;
display: none;
}

#auditorio
{
text-align: center;
width: 100%;
margin: 0 auto;
display: none;
}

JQuery:

Comment: Uai jovem, cade o link de indexação do jQuery na sua página??
Comment: Ah, agora que vc editou tudo bem...! Mas vc deveria usar uma verão mais nova tipo a 3.1 ou 3.2... não que isso vá resolver o problema com certeza, mas é uma boa prática usar as versões mais novas se não afetar seu script
Comment: Qual é a versão do Bootstrap que vc está usando?
Comment: Por favor, passe o link da sua página que está dando problema na internet
Comment: Confere na Aba "Network" do Chrome DevTools se todos os arquivos .JS estão sendo carregados na página
Comment: Estou usando link CDN ()
Comment: Entendi, vou trocar por uma versão mais atualizada. Obrigado pela dica!!
Comment: Consegui resolver o problema. Muito obrigado!!
Estava ocorrendo um conflito em um dos trechos do código.
Estou usando a versão 4.0.0 do Bootstrap
Aqui está o link: http://www.garotodati.com.br/divsMostrar
Answer: Seu código tem muita redundância, começando pelo CSS: se as ids são exatamente iguais, você não precisa repetir separados, pode declarar as duas ao mesmo tempo. E também não precisa setar width: 100% e margin: 0 auto já que a div ocupa toda a largura de onde está, além do mais você já está centralizando o texto com text-align: center;. Então ficaria apenas assim:
#carimbo, #auditorio{
   text-align: center;
   display: none;
}

Outra coisa desnecessária é essa função ocultar(). Além do que você mistura JavaScript puro usando document.getElementById('carimbo').style.display = 'none'; quando poderia apenas usar o método .hide() do jQuery com os dois ids ao mesmo tempo como seletor, e pode fazer isso dentro do próprio evento .click sem a necessidade de chamar outra função só para fazer isso.
$('#carimbo, #auditorio').hide();

Seu código otimizado fica assim:

$(document).ready(function(){
   $('.conteudoDiv').on('click', function(e){
      $('#carimbo, #auditorio').hide();
      e.preventDefault();
      var el = $(this).data('element');
      $(el).slideToggle('slow');
   });
});
#carimbo, #auditorio{
   text-align: center;
   display: none;
}

<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">

Solicitar Carimbo

Portaria

Carimbo

Auditorio

Também não precisa declarar o type="text/javascript" do script. Isso
  já não é mais necessário no HTML5.
Comment: Entendi. Obrigado pelas dicas!!


Why com.sun.management.ThreadMXBean not functioning on Ant?

Question: I have a test case which requires  com.sun.management.ThreadMXBean, to retrieve thread info. When I run this test case on eclipse it works but when I run from ant - junit task. it throws the following..
Here's my code snippet, How can get it working in ant ? Thanks.

 ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
com.sun.management.ThreadMXBean comSunThreadMXBean = (com.sun.management.ThreadMXBean)threadMXBean;
Answer: Fixed it with adding fork=true


Signed and unsigned integers with logical operators

Question: int x = /* some integer */;
unsigned int ux = (unsigned) x;

we have
x >= 0 || x < ux

we know that in x < ux the first x is cast implicitly to unsigned but is the first x in x >= 0 (1) cast to unsigned implicitly?
Comment: Detail: `x` is not _cast_ - there is no cast in `x < ux`.  `x` is _converted_ to an `unsigned`.
Answer: No. It happens operator by operator.
x >= 0 || x < ux

is naturally
(x >= 0) || (x < ux)

Since x and 0 are both ints, there is no need for any (usual arithmetic) conversions...
And even though x is converted to unsigned in x < ux, the value of the expression x < ux is of type int - either 0 or 1 (just like on the the left-hand side).
Answer: No it isn't.
This is because x >= 0 is an expression. (Formally 0 is an octal constant of type int.)
Try 1 / 2 * 1.0 for a more pernicious example. This is grouped as (1 / 2) * 1.0 and is zero since the integers in the expression 1 / 2 are not promoted to floating point.
Comment: Thanks, makes sense
Answer: No, 0 is an int, so there are no promotions in the x >= 0 part of your expression.


Android Management API - Setting issue

Question: I am working on Android Managament API by Google. I need to disable all possibile access to menu settings except to "Wifi Menu". I am using a Kiosk App.
Now, I disabled the access from the policy but I still am to able to access and navigate in menu system with a simple click on the back arrow button in the left top corner from opening the wifi menu.
image url
is It a google bugs?
My policy is:
"kioskCustomization": {
    "statusBar": "NOTIFICATIONS_AND_SYSTEM_INFO_ENABLED",
    "deviceSettings": "SETTINGS_ACCESS_BLOCKED",
    "systemNavigation": "HOME_BUTTON_ONLY",
    "powerButtonActions": "POWER_BUTTON_BLOCKED"
},

Answer: I don't think there is a feature in AMAPI where you can only access the WIFI menu. About the deviceSettings:"SETTINGS_ACCESS_BLOCKED", it will block all the settings menu and you should not be able to navigate in the menu system. I tried using this on public apps like Instagram, Youtube and a private app but I wasn't able to access the Menu Settings using the back arrow button.
In the other scenario I made, I created a private app to access WIFI Menu using a settings intent like WifiManager.ACTION_PICK_WIFI_NETWORK and  I was able to access the Menu System.
We have identified a bug that is currently being investigated by our Engineering team and for which a fix is about to be released.
I suggest joining the Android Management API mailing list to keep you posted on the latest updates.

Android Management API - Setting issue


OSError: [Errno 22] Invalid argument: 'D:\\pyCHram\\'

Question: I use 'ProcessPoolExecutor' to handle some data on PyCharm,but i get this error:"OSError: [Errno 22] Invalid argument: 'D:\pyCHram\'"。
But I don't know why, I dont write any code about the file path.
'D:\pyCHram\' is the folder that i save python file.  Thank you very much for answering my questions.
The part of the code is below:
if __name__ == '__main__':
    data_result = []
    startTime = datetime.datetime.now()
    pool = ProcessPoolExecutor(3)
    for i in range(3):
        future = pool.submit(search,poolArgsList[i],data_1)
      ###poolArgsList[i] and data_1   both areparameter.
        data_result.append(future)
    endTime = datetime.datetime.now()
    print((endTime-startTime).seconds)

Comment: Please create a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) and post the full error traceback!
Answer: That does look like an error I bit my teeth out once.
In my case, it did not happen, once executed from terminal instead of PyCharm's console.
A workaround was to set __file__ = 'workaround.py' (an empty file in the directory of your project).
Got the workaround from the comments of the open issue at jetbrains: https://youtrack.jetbrains.com/issue/PY-36151/Can-t-create-Pool-in-multiprocessing-in-Python-Console
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


postgresql drop table

Question: I have two tables (tbl and tbl_new) that both use the same sequence (tbl_id_seq).  I'd like to drop one of those tables.  On tbl, I've removed the modifier "not null default nextval('tbl_id_seq'::regclass)" but that modifier remains on tbl_new.  I'm getting the following error:
ERROR:  cannot drop table tbl because other objects depend on it
DETAIL:  default for table tbl_new column id depends on sequence tbl_id_seq
After reviewing http://www.postgresql.org/docs/9.1/static/sql-droptable.html
It looks like there is only CASCADE and RESTRICT as options.
Comment: how did you create the tbl_id_seq? and how do you drop tbl? Please provide some code. (I just tested it and it worked fine for me so most likely the problem is in a detail thats not provided here.)
Answer: You need to decouple the sequence and the table it "belongs" to:
ALTER SEQUENCE "tbl_id_seq" OWNED BY NONE;

I suppose it was created automatically (and "bound") by defining the tbl_id field of tbl as SERIAL.
Answer: To find sequences and all tables that depend on them via column default:
SELECT sn.nspname || '.' || s.relname AS seq
      ,tn.nspname || '.' || t.relname AS tbl
FROM   pg_class s
JOIN   pg_namespace sn ON sn.oid = s.relnamespace
LEFT   JOIN pg_depend d ON d.refobjid = s.oid AND d.deptype <> 'i'
LEFT   JOIN pg_attrdef ad ON ad.oid = d.objid
LEFT   JOIN pg_class t ON t.oid = ad.adrelid
LEFT   JOIN pg_namespace tn ON tn.oid = t.relnamespace
WHERE  s.relkind = 'S'
AND    s.relname ~~ '%part_of_seq_name%' -- enter search term here
ORDER  BY 1,2;

Now with LEFT JOIN to show "free-standing" sequences as well.
You can then use the method @Milen posted to make the sequence "free-standing".
I posted a related answer a few days ago.

postgresql drop table


como pegar JsonProperty.Name

Question: tenho a seguinte classe:
    public class Planilha
{
    public string CNPJ { get; set; }
    public string Status { get; set; }
    public string Contrato { get; set; }
    public string Vencimento { get; set; }
    public string Acesso { get; set; }

    [JsonProperty("Razão Social")]
    public string RazaoSocial { get; set; }

    [JsonProperty("Nome Fantasia")]
    public string NomeFantasia { get; set; }
    public string Parceiro { get; set; }
    public string Cidade { get; set; }
    public string UF { get; set; }
}

em um momento do codigo eu tenho um array de Planilhas, percorro esse array e para cada propriedade preciso pegar esse JsonProperty
foreach (PlanilhaPrecisao item in planihaPrecisao)
            {
                var x = "nome da propriedade /* ou JsonProperty";

            }

ou seja, quando chegar na propriedade RazaoSocial  eu preciso que x seja igual  "Razão Social", como faço isso ?
Comment: não está bem claro, no exemplo tem a classe "Planilha" e no foreach "PlanilhaPrecisao"
Answer: Utilize Reflection para acessar os atributos de uma propriedade.
PropertyInfo[] todasAsPropriedadesDePlanilha = typeof(Planilha).GetProperties();

Dessa forma voce tem acesso a todas as propriedades que existe em Planilha.
Entao voce pode facilmente percorrer essas propriedades e acessar os atributos que ela possui.
Como voce sabe que precisa de JsonPropertyAttribute basta usar o metodo GetCustomAttribute que esta dentro de PropertyInfo.
Veja o exemplo abaixo onde eu estou percorrendo todas as propriedades de Planilha.
using Newtonsoft.Json;
using System.Reflection;

foreach (PropertyInfo property in typeof(Planilha).GetProperties())
{
    string nomePropriedadeOuValorAtributo = string.Empty;
    var atributo = property.GetCustomAttribute<JsonPropertyAttribute>();
    if (atributo != null)
    {
        nomePropriedadeOuValorAtributo = atributo.PropertyName;
    }
    else
    {
        nomePropriedadeOuValorAtributo = property.Name;
    }
}

De acordo com a pergunta voce precisa de JsonProperty ou o nome da propriedade, eu adicionei uma simples condição caso nao exista o atributo.
Dentro de PropertyInfo tambem existe o metodo GetProperty onde ele recebe como parametro o nome da propriedade. Entao se voce quer acessar o atributo da sua propriedade RazaoSocial aplicando em seu codigo, ficaria mais ou menos dessa forma.
foreach (PlanilhaPrecisao item in planihaPrecisao)
{
     string nomePropriedadeOuValorAtributo = nameof(item.RazaoSocial);
     PropertyInfo propertyInfo = typeof(Planilha).GetProperty(nomePropriedadeOuValorAtributo);
     var atributo = propertyInfo.GetCustomAttribute<JsonPropertyAttribute>();
     if (atributo != null)
     {
          nomePropriedadeOuValorAtributo = atributo.PropertyName;
     }
}

como pegar JsonProperty.Name


Time of MySQL database removal

Question: Is there a method where we could probably find when a MySQL database was removed/dropped from the server? Is this logged anywhere? Does it have a separate logfile which probably needs to be enabled in the configuration file?
Additionally, this is a cPanel server, but there's nothing logged in the cPanel access-logs (or error-logs for that matter). DROP TABLE, too doesn't specify anything in this regard (from 5.0 to 5.6).
Thanks in advance.
EDIT: The database that was deleted was an InnoDB database. (thankfully, we have backups)
As @longneck suggested, I checked BINLOG EVENTS, using the information in this question but this seems disabled at the moment.
mysql> SHOW VARIABLES LIKE 'log_bin';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| log_bin       | OFF   |
+---------------+-------+
1 row in set (0.01 sec)

Comment: How was the database stored? Innodb? Memory? MyISAM?
Comment: Administration panels are off-topic on Server Fault.
Answer: If binary logging is enabled, you can use SHOW BINLOG EVENTS statement or the mysqlbinlog utility to search the binary logs for DROP statements.

Time of MySQL database removal


vsftp hangs at "150 Here comes the directory listing."

Question: In a vsftpd server enviroment, shared various directories from nfs mountpoints, I can log in without problem, but when I send the first "ls", the vsftp give me the directory listing:
lftp email@example.com:~> ls
-rw-rw-rw-    1 1160     1016          392 Jun 06 09:28 test.gif

but not give me the shell again (lftp client). In the server log I can see that the last message is:
"150 Here comes the directory listing."

Why does this happen?
Answer: Check your firewall settings, chances are you are not allowing the PASV ports through, or maybe port 20 ftp-data. Try opening TCP ports 50000-55000 on your firewall and add the below to your vsftpd.conf.
pasv_min_port=50000
pasv_max_port=55000

If using active mode then you should just need port 20, if using passive then you should be setting those ports on your firewall and the matching in the ftp config.
Here is a quick overview on Active vs Passive
http://slacksite.com/other/ftp.html
Answer: I had that same problem on my Amazon EC2 Ubuntu machine. I had ports 50000-51000 set for the passive mode in vsftpd.conf, and I had to open the ports on the security group AWS firewall settings.


Admin account has it's own log in form and should not be able to log in in default log in form

Question: I have this certain problem which I don't know how to start doing this thing.
In drupal we have a log in form (let's call it normal login form) which all users can log in including admin.
So what I want is, to create a log in form for admin only. Which I already made it.
But the problem lies here, the normal login form should not let the admin proceed if the admin log in at the normal log in form
Here's a screenshot for it.
As you can see, that's the normal log in form. If the admin logged in to that, it should not let them proceed since they have their own log in form. All I want is only normal users can access can log in in this form.

Any possible solution for this?
Comment: Probably many, but why exactly you feel you need that separation? We don't want a solution to work around your true goal, after all.
Answer: You could implement hook_form_alter or hook_user_login() to check the roles of the user logging in and deny if the user is an administrator. Check the Examples module for uses of hook_form_alter and other contrib modules like Legal and User Auth API are practical examples of extra validation and control during user authentication.


Class Não Encontrada no Laravel 5

Question: Tenho esse Controller no Laravel 5.
HomeController.php
<?php namespace App\Http\Controllers;

    use View;
    use App\Portfolio;
    use App\Cliente;

    class HomeController extends Controller {

    public function getIndex(){

        # PORTFOLIO - Separado em Três Partes no Owl Carousel
        $portfolio['um']    = Portfolio::take(5)
                              ->whereStatus(1)
                              ->get();

        $portfolio['dois']  = Portfolio::skip(5)
                              ->whereStatus(1)
                              ->take(5)
                              ->get();

        $portfolio['tres']  = Portfolio::skip(10)
                              ->whereStatus(1)
                              ->take(5)
                              ->get();

        return view('frontend.home')
               ->withPortfolio($portfolio);
    }

}

Ele faz um extends do Controller.
E dentro desse Controller criei uma função.
<?php namespace App\Http\Controllers;

use Illuminate\Foundation\Bus\DispatchesCommands;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;

abstract class Controller extends BaseController {

    use DispatchesCommands, ValidatesRequests;

    # Nome do Cliente no Portfolio
    static function NomeCliente($cliente){
        $explode    = explode(' ', $cliente);
        $varCliente = $explode[0].' '.$explode[1].'';

        return $varCliente;
    }

}

View

{!! Controller::NomeCliente($item->client->nome_fantasia) !!}

Depois na View eu chamo essa função pelo Controller, como eu sempre fazia no Laravel 4.2.
Mas agora acontece esse erro:

Class 'Controller' not found

O que está errado ou faltando ?

Eu criei um novo controller, chamado NewController.php apenas para teste.
Mesmo assim na View quando a chamo, também diz que não foi encontrada.

Resolução
Consegui resolver da seguinte maneira:
Colocando o caminho completo do Controller na View. Ex:
{!! App\Http\Controllers\URLController::Link('quem-somos') !!}
Comment: o arquivo da Class ta com o nome igual da Class?
Comment: Sim. Resolvi a parada. Mas dentro do meu controller tem um **Request**, que não funciona. Dá o seguinte erro: **Non-static method Illuminate\Http\Request::segment() should not be called statically**
Answer: Resolução
Consegui resolver da seguinte maneira:
Colocando o caminho completo do Controller na View. Ex:
{!! App\Http\Controllers\URLController::Link('quem-somos') !!}

Class Não Encontrada no Laravel 5


Prove that the nuclear norm is convex

Question: For an $m \times n$ matrix, $A$, the nuclear norm of $A$ is defined as $\sum_{i}\sigma_{i}(A)$
where $\sigma_{i}(A)$ is the $i^{th}$ singular value of $A$.   I've read that the nuclear norm is convex on the set of $m \times n$ matrices.   I don't see how this true and can't find a proof online.
Answer: It is sufficient to prove that the nuclear norm is, in fact, a norm. It's trivial to verify that $\|A\|=0$ only if $A=0$, and that $\|tA\|=|t|\|A\|$ if $t$ is a scalar. The one non-trivial requirement is that the norm satisfies the triangle inequality; that is,
$$\|A+B\|\leq \|A\|+\|B\|.$$
To do that, we're going to prove this:
$$\sup_{\sigma_1(Q)\leq 1} \langle Q, A \rangle =
\sup_{\sigma_1(Q)\leq 1} \mathop{\textrm{Tr}}(Q^HA) = \sum_i \sigma_i(A) = \|A\|.$$
Since $\sigma_1(\cdot)$ is itself a norm, what we're actually proving here is that the nuclear norm is dual to the spectral norm.
Let $A=U\Sigma V^H=\sum_i \sigma_i u_i v_i^H$ be the singular value decomposition of $A$, and define $Q=UV^H=UIV^H$. Then $\sigma_1(Q)=1$ by construction, and
$$\langle Q, A \rangle = \langle UV^H, U\Sigma V^H \rangle = \mathop{\textrm{Tr}}(VU^HU\Sigma V^H)
= \mathop{\textrm{Tr}}(V^HVU^HU\Sigma) = \mathop{\textrm{Tr}}(\Sigma) = \sum_i \sigma_i.$$
(Note our use of the identity $\mathop{\textrm{Tr}}(ABC)=\mathop{\textrm{Tr}}(CAB)$; this is always true when both multiplications are well-posed.)
So we have established that
$\sup_{\sigma_1(Q)\leq 1} \langle Q, A \rangle \geq \sum_i \sigma_i(A)$.
Now let's prove the other direction:
$$\sup_{\sigma_1(Q)\leq 1} \langle Q, A \rangle =
\sup_{\sigma_1(Q)\leq 1} \mathop{\textrm{Tr}}(Q^HU\Sigma V^H) =
\sup_{\sigma_1(Q)\leq 1} \mathop{\textrm{Tr}}(V^HQ^HU\Sigma) =
\sup_{\sigma_1(Q)\leq 1} \langle U^HQV, \Sigma \rangle =
\sup_{\sigma_1(Q)\leq 1} \sum_{i=1}^n \sigma_i (U^HQV)_{ii} =
\sup_{\sigma_1(Q)\leq 1} \sum_{i=1}^n \sigma_i u_i^H Q v_i \leq
\sup_{\sigma_1(Q)\leq 1} \sum_{i=1}^n \sigma_i \sigma_\max(Q) =
\sum_{i=1}^n \sigma_i.
$$
We have proven both the $\leq$ and $\geq$ cases, so equality is confirmed.
Why did we go through all of this trouble? To make proving the triangle inequality easy:
$$\|A+B\|=\sup_{V:\sigma_\max(V)\leq 1} \langle V, A+B \rangle
\leq \sup_{V:\sigma_\max(V)\leq 1} \langle V, A \rangle +
\sup_{V:\sigma_\max(V)\leq 1} \langle V, B\rangle = \|A\| + \|B\|.$$
Comment: I could not. I came up with this on my own, without references. That is _not_ to suggest that it is original to me, just that I couldn't tell you where I obtained the necessary knowledge.
Comment: Can you tell me, in which book I can find these proofs?
Comment: Thank you for the answer. In that case, could you please explain how did you derive this: $\sup_{V:\sigma_\max(V)\leq 1} \langle V, A+B \rangle
\leq \sup_{V:\sigma_\max(V)\leq 1} \langle V, A \rangle +
\sup_{V:\sigma_\max(V)\leq 1} \langle V, B\rangle$
Comment: @Michael Grant : In the first part, I understand taking the $\sup$ has to be done to get the result but $Q=UV^H$ is a unique matrix. Over what you are taking the $\sup$?
Comment: @Saeed you're right, $Q=UV^H$ is a _single value_ from among all of the possible values of $Q$ satisfying $\sigma(Q)\leq 1$. By computing the value for this single point, it establishes a _lower bound_ for the supremum. After all, it is universally true that $\sup_x f(x) \geq f(x_0)$ for any fixed $x_0$.
Answer: Any norm is convex. If $0 \leq \theta \leq 1$, then $\| \theta x + (1 - \theta) y \| \leq \|\theta x \| + \| (1-\theta) y \| = \theta \|x\| + (1-\theta) \| y\|$.
Comment: Yeah that's right.  So I guess my question is why is the nuclear norm a norm?

Prove that the nuclear norm is convex


XenApp Web interface: User loging from two different browsers or machines -> Disconnected session

Question: I have an issue with our new Citrix XenApp 6.5 deployment with Web Interface 5.4 and CSG 3.3.1
We have external users who share the same access (we charge them by access so they don't order more than they need and manage that internally). This setup was working just fine with XenApp 4.5: users could log into the web interface twice but, when they tried to access the same published app, they would not be allowed to go through and be greeted with a "you have reached the limit of allowed sessions for this resource" dialog.
Now, with 6.5 (and Citrix web interface 5.4), we have a different behavior: as soon as the second user logs into the WI, the first user's session is disconnected. Pretty often (but, apparently, not every time) the second user will automatically reconnected to the first user's session.
I suspect that this behavior is due to the session reliability parameter but I'd like a confirmation.
More important: If it is indeed session reliability that is causing this behavior, is it possible to maintain its advantages (mostly ability to seamlessly reconnect THE SAME RECEIVER to its session in case of network glitch or if we restart the CSG) without having "auto reconnection at web interface level" enabled ?
Answer: Of course, after asking the question I found the solution on my own :/
In case anyone ends up here, the solution is this:
Go in the web interface management tool, select the web site, right-click and select "workspace control" and there select the "Reconnect only to disconnected sessions" radio (I did it for both auto reconnect and the reconnect button)
Comment: I've taken "Solved" out - just mark this answer as correct when you can


Storing Activity context in Bundle

Question: I am using static factory method to create fragment. But I need to use activity's context in the fragment and therefore I need to wrap that context into a bundle and attach it to the fragment using setArguements() method so that I can retrieve it later.
But if I try to store context by doing bundle.putSerializable("tag", context) -> it throws an error. Can anyone tell me how to wrap activity context into a bundle?
Comment: Why man.. Why you can not use `getActivity()` method in your Fragment?
Answer:
But I need to use activity's context in the fragment

You do not need it in most cases. All you need is to use getActivity() in your fragment instead.
Comment: @allstraws see this question on how to get context in a fragment http://stackoverflow.com/questions/8215308/using-context-in-fragment
Comment: @allstraws you cannot get it always (i.e. you won't get it in your `getInstance()` implementation or constructor), but you basically need activity only when you are part of it, and in such case `getActivity()` is what you are looking for.
Comment: does that mean we never need to pass any context to a fragment because it can always be obtained through getActivity()?

Storing Activity context in Bundle


What does $y = Ar^t$ mean?

Question: I keep coming up in this question and its variants in my math tests, but it has not been explained to me so I can't really answer it. As such, I am at risk of failing the year.
An example question is as below:

Bob bought a farm in 1980. In 2017 he sold it for $500,000 and calculated it rose exponentially at a rate of 4% over that time.
(i) Assuming that it increased in value according to the formula $y = Ar^t$, where $A$ is the purchase price and  $^t$  is the time in years, what was his profit?

As you can see, the values of $A$ and $^t$ are pretty clearly defined, and $y$ is implicitly defined, but nowhere is the value $r$ defined.
So what is $r$ supposed to be, and how would I go about answering this question?
Comment: Where are you using the rate of 4%?
Comment: @KitterCatter the question specifies that
Comment: I am not sure what 'exponentially at a rate of 4%' means. Naively I would do something like $y(t) = A (1.04)^t$.
Comment: @KitterCatter: Yes, but I would have expected the wording to reflect that. When I see exponential in finance I think continuous compounding.
Comment: Usually continuous compounding would result in something like $y(t) = A e^{0.04 t}$.
Comment: @copper.hat And so $r=e^{0.04}$, no?
Comment: @amd: That is correct.
Answer: The $r$ means rate of increase of the price, which is $1 + 4\% = 1.04$.
$$t = 2017 - 1980 = 37 \text{ years}$$
$$y = $500000$$
Now we calculate the value of $A$, which is the purchase price of the farm in 1980.
$$\begin{array}{rcll}
y &=& Ar^t\\
500000&=&A\left(1.04\right)^{37}\\
A&=&\dfrac{500000}{(1.04)^{37}} \\
&\approx&$117148.42
\end{array}$$
Now, the profit is $\text{Selling price} - \text{Purchase price}$:
$$\begin{array}{rcll}
\text{Profit} &=& $500000 - $117148.42\\
&\approx&$382851.58
\end{array}$$
To clarify, $y = Ar^t$ is an exponential equation. Usually $r$ denotes the rate of increase, or the rate of decrease as $r$ stands for "rate".
Comment: Actually, the increase is exponential, not the rate, which is flat.

$1.04^t$ is exponential as $^t$ increases
Comment: This is standard compounding, but the question specifies an exponential rate.
Answer: I am not sure what is mean by exponential rate, but assuming that it means continuous compounding, we have the formula
$y(t) = A e^{0.04 t}$, with $t$ in years.
Hence $y(2017) = y(1980) e^{0.04 (2017-1980)} = 500000$ from which can compute $y(1980)$. Then the profit is given by $y(2017)-y(1980) \approx 386181$.
Comment: My notation is a bit inconsistent above but you get the idea.
Answer: The exponential function is:
$$f(x)=ab^x,b>0.$$
Now $b$ can take various values, in particular:
$$b=1+\frac{0.04}{m},m\ne 0$$
Note that when $m=1,2,4,12$, it is the annual, semi-annual, quarterly, monthly interest compounding, respectively. For example, for $x\in \mathbb N$:
$$f(x)=a(1+0.04)^x=a\underbrace{(1+0.04)(1+0.04)\cdots (1+0.04)}_{x}\\
f(x)=a\left(1+\frac{0.04}{2}\right)^{2x}=a\underbrace{\left(1+\frac{0.04}{2}\right)\left(1+\frac{0.04}{2}\right)\cdots \left(1+\frac{0.04}{2}\right)}_{2x}.$$
When $m\to \infty$, the formula of continuous interest compounding becomes:
$$f(x)=\lim_\limits{m\to \infty} a\left(1+\frac{0.04}{m}\right)^{mx}=ae^{0.04x}.$$
=========================================================================
The OP's problem suggests the exponential function $y=Ar^t$. However, it can be interpreted in two ways:
$$y(t)=Ar^t=A(1+0.04)^t=Ag(t)$$
or:
$$y(t)=Ar^t=A(e^{0.04})^t=Ag(t)$$
Note: The first is an ordinary exponential function, while the second is a natural exponential function.
Once it is clarified, the rest is a simple calculation with
$$\begin{align}y(0)&=A,\\
t&=2017-1980=37,\\
y(37)&=500,000\\
\text{Profit}&=\frac{y(37)}{A}=\frac{500,000}{A}=g(37) \ \ \text{(in percentage of the purchase price)}\\
\text{Profit}&=y(37)-A=\\
&=500,000-\frac{y(37)}{g(37)}=\\
&=500,000-\frac{500,000}{g(37)}\ \ \text{(in dollars)}\end{align}$$

What does $y = Ar^t$ mean?


Determine whether S is a subspace of V, if yes find a basis and its dimension.

Question: So this here questions got me stuck for a bit:

Determine whether S is a subspace of V, if yes find a basis and its
  dimension. Let $S$ be the set of all 3x3 symmetric matrices in $V =
 M_{3x3}$

And here's why: I checked the appropriate axioms and it turns out S is in fact a subspace of V, but my main problem is that before this exercise, to find a basis, I'd find the augmented matrix and solve it (RREF) and then determine the solution, but here I'm not sure if I can.
So I have an approach but not sure which if it works:
If I say for e.g.
Assume the matrix $A=\begin{pmatrix}
    a &  b & c\\
    b & d & e\\
    c & e & f\\ \end{pmatrix}$
if det(A) $\neq 0$ => linearly independent => the basis exists.
$k_1\begin{pmatrix}
    a\\
    b\\
    c\\ \end{pmatrix}$
+ $k_2\begin{pmatrix}
    b\\
    d\\
    e\\ \end{pmatrix}$
+ $k_3\begin{pmatrix}
    c\\
    e\\
    f\\ \end{pmatrix} = 0;
dim(S) = 3$
Please let me know how to go about this. Thank you.
Comment: @DietrichBurde it is the same question, but my approach was not explained there.
Comment: Your approach is explained in the duplicate. For example, the matrix with parameter $b$ is $E_{12}+E_{21}$ from the answer there, and for $a$ it is $\frac{1}{2}(2E_{11})=E_{11}$.
Answer: Hint. The vector space $V$ is $9$-dimensional. How many of the $9$  entries can you specify independently in a $3 \times 3$ matrix and have it be symmetric. Clearly not all $9$.


SVG / XML: Remove unwanted XML / SVG www.w3.org/2000/svg tags?

Question: We like mixing SVG code with JQuery templates.  When we save SVG graphics from Adobe Illustrator or Inkscape, they have more than just the xmlns="http://www.w3.org/2000/svg" namespace tags, having proprietary "hints" or code that will be ignored in a HTML 5 browser.
We want to create graphics in Inkscape for example, then use them without having to manually cherry pick the unwanted, ignored tags, possibly even formatting them.
Is there code out there that could remove or minify the non-compliant svg tags produced by these programs based on xmlns="http://www.w3.org/2000/svg"?
We will use ASP.NET MVC 3 to supply these templates using JQuery .ajax calls, so there's the potential of a C# XML "cleaner" based on a namespace?
Answer: Check out Jeff Schiller's tool Scour: http://www.codedread.com/scour/
Comment: I had to flip a quarter between the answers.  This answer is very correct and useful too.
Answer: If you can use XSLT, the following transform will drop all elements that are not in the SVG namespace:
<xsl:stylesheet version="1.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:svg="http://www.w3.org/2000/svg">

<xsl:template match="svg:*">
  <xsl:copy>
    <xsl:copy-of select="@*[namespace-uri()='']"/>
    <xsl:apply-templates select="node()"/>
  </xsl:copy>
</xsl:template>

<xsl:template match="*"/>

</xsl:stylesheet>

A little care is need to handle attribute correctly.  Some SVG editing software will add additional attributes, so when we copy attributes, we only copy those in the default namespace so non-SVG standard attributes will also get stripped.
Comment: In order to not lose a few `xlink:href` to defined gradients had to add a second `xsl:copy-of` right next to the first one, for the xlink namespace, saying `` .


How to add a property to an object at a specific index of an array in typescript (Angular)?

Question: emailData.contractors = [
                    0: {
                         id: 1,
                         email: asd@asd
                       }
                    1: {
                         id: 1,
                         email: asd@asd
                       }
                  ]

emailSub(event, data) {
    const trigger = $(event.target);
    this.emailData.contractors.forEach((v, i) => {
      if (v.id == data.id) {
        this.emailData.contractors[0]['subject'] = trigger.val();
      }
    });
  }

Expected Output
                    0: {
                         id: 1,
                         email: asd@asd
                         subject: 'sdf'
                       }
                    1: {
                         id: 1,
                         email: asd@asd`enter code here`
                       }
                  ]

How can i achive this in angular 8. the function above is not working on a keyup of an input from which i get the data
Comment: `[
                    0: {` is not valid syntax
Answer: Use Object.assign to add an property.
Try like this:
emailSub(event, data) {
   const trigger = $(event.target);
   let item = this.emailData.contractors.find(x => x.id == data.id);
   Object.assign(item, {'subject':trigger.val()})
}

Working Demo
Answer: change your data to
emailData.contractors = [
                {
                     id: 1,
                     email: "asd@asd"
                },
                {
                     id: 2,
                     email: "asd@asd"
                }
              ]

Or
emailData.contractors = {
                0: {
                     id: 1,
                     email: "asd@asd"
                },
                1: {
                     id: 2,
                     email: "asd@asd"
                }
              }

Comment: is my function should work,,,, those data is for example ... i got the emailData.contractors from an api  like this
``` data: [,…]
0: {company: "ABC Maintenance", address: "17/52 Holker Street", preferred: 0, phone: "(03) 9508 5588 ",…}
1: {company: "AZ Electrician", address: 13, preferred: 0, phone: "(02) 9875 0000 ", fax: "9522 1111",…}
2: {company: "AZ Plumbing", address: "Sydney", preferred: 0, phone: "(02) 9443 8899 ", fax: "9887 6677",…}
```