Clabel and createText not in align

Question: When i create a label and multiline text.
I see the result as below -

But i want the label to be at the top and not in center of the multiline text field.
I want the result as below -

Here is the code -
<code>getWidgetFactory().createCLabel(parent, Configuration, SWT.LEFT); //$NON-NLS-1$
 Text configuration = getWidgetFactory().createText(parent, "",SWT.MULTI|SWT.V_SCROLL|SWT.H_SCROLL);
GridData dataConfig = new GridData();
dataConfig.widthHint = 175;
dataConfig.heightHint = 175;
configuration.setLayoutData(dataConfig);
</code>
Comment: You should take a look at the layout examples that are given here: https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html
This way, you can make an educated choice on which layout to pick for your entire GUI, which depends on what other components you'll be adding and where.
Comment: thanks, but its a legacy project, i cant make a choice now on that. I have just the authority to edit it and make the requested change
Comment: Alternatively, you can create a new `CLabel` and set its x-y position directly. If your application can be resized in a way such that the label should change position, then this does mean that you have to add a resize listener for this. That's one reason why layout managers are preferred when possible.
Comment: I just now found out the solution for it, using GridData for label too and set it to SWT.TOP, it solves the issue
Answer: Using GridData for label too and set it to SWT.TOP, it solves the issue.
GridData labelData = new GridData();
labelData.verticalAlignment = SWT.TOP;
Using the above Griddata set the layout for the label.

Clabel and createText not in align


Linux - setting Code::Blocks to compile multithreading C++ code

Question: I have searched through forums here, but nothing helped to the end in my case.
I'm trying to write and compile some C++ multithreading code in Code::Blocks 13.12, for now the only code I have is:
<code>#include <iostream>
#include <thread>

void cpp11()
{
    std::cout<<"C++11 MULTITHREADING\n";
}

int main()
{
    std::thread t(cpp11);
    t.join();
}
</code>
Initially I could not compile and run that code (both in Code::Blocks and Terminal) because I was getting an error:

Terminate called after throwing an instance of 'std::system_error'
  what(): Enable multithreading to use std::thread: Operation not
  permitted.

I found that I'm able to compile and run that code calling g++ in the Terminal like that:
<code>g++ -std=c++11 -pthread main.cpp -o Program
</code>
but I cannot set the same in Code::Blocks.
I went to Project -> Build options, in the Compiler settings tab I selected Have g++ follow the C++11 ISO C++ language standard [-std=c++11].
In the Compiler settings -> Other options I typed -pthread.
In Linker settings -> Other linker options I typed -pthread.
It does not work, after I build and run my project in Code::Blocks I get the same error message.
Thank you for any help!
Comment: I don't have nothing like "Advanced options" in Build settings -> Compiler settings.
Answer: Follow instructions for this question
How do I link to a library with Code::Blocks?
in the last step, when Add library dialog pops up type pthread.
UPDATE
Again go to build options > Compiler settings . click on other options and type -pthread
Comment: I just did like you advised - it did not help. pthread is added but is still gives me the same error.
Comment: @ikS11 can copy and paste commands that code blocks run to here? you can see them in build log.
Comment: Here you have the Build log's output after build and run:
Checking for existence: /home/dawid/MyProject/bin/Debug/MyProject
Executing: xterm -T MyProject -e /usr/bin/cb_console_runner LD_LIBRARY_PATH=$LD_LIBRARY_PATH:. /home/dawid/MyProject/bin/Debug/MyProject  (in /home/dawid/MyProject/.)
Process terminated with status 0 (0 minute(s), 2 second(s))
Comment: Eh, some fun happened.... I changed the settings as you advised, but I did not change anything in the code, so the code was not build from the beginning... Works perfectly fine now after rebuild, thank you!


How to install APK stored in internal memory without SD Card

Question: I've been trying to find out how to install stored APK from internal memory, but I continually get errors.
I've tried getFilesDir() but it returns
08-14 03:18:09.127 10089-10089/? W/zipro: Error opening archive /data/user/0/package_name/files/app-release.apk: I/O Error

08-14 03:18:09.127 10089-10089/? D/asset: failed to open Zip archive '/data/user/0/package_name/files/app-release.apk'

08-14 03:18:09.127 10089-10089/? W/PackageInstaller: Parse error when parsing manifest. Discontinuing installation

I've also tried Environment.getDownloadCacheDirectory() but I get a similar result.
I am attempting to install on a non-rooted device, but I have signature level app permission.
How do I install app on a non-rooted device?
Even
public void installAPKManual(String filename) {
    Intent intent = new Intent(Intent.ACTION_VIEW);
    Uri uri = Uri.fromFile(new File(filename));
    intent.setDataAndType(uri, "application/vnd.android.package-archive");
    startActivity(intent);
}

doesn't work. Parse error.
Update
It works after I use
file.setReadable(true, false)

to get world readable permission, but I wonder if there is a better way?
Comment: Have you tried?  intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Answer: If you are trying to retrieve the file from Environment then you need storage permission.
or if you are trying to get the file from your private storage getCacheDir() or getFileDir() you don't need permission but you must use File Provider.
if these are not the case try to install the APK manually first and see that everything is ok with the APK or not!!!
Comment: i have all the permissions... read, write, etc. I think it's just linux permissions.
Comment: did you try to install the APK manually?
is everything alright with APK


Contour Integral $\oint\limits_{C}\mathrm{d}z \,\sqrt{\frac{z-a}{z-b}}$

Question: $C$ is any closed curve encompassing the whole branch cut.
The approach to this problem would involve using the residue theorem:
1) We first want to find the residues at infinity so we change the form to where we are able to perform a series expansion.
2) Obtain the coefficients of $\frac{1}{z}$.
3) Plug the residues back into the formula: $\oint\limits_{C}\mathrm{d}z \, f(z)=2\pi i \, \mathrm{Res}(f,\infty)$
So for the integral: $\oint\limits_{C}\mathrm{d}z \,\sqrt{\frac{z-a}{z-b}}$
I would like some help in obtaining the form which allows for an expansion. If this approach is bad for this integral, then please inform me of a better solution.
A similar problem has been posted before here, for which $\oint\limits_{C}\mathrm{d}z \,\sqrt{(z-a)(z-b)} = \dfrac{\pi i}{4}(a-b)^2$. I am just referencing this because the problem is so similar as with our approach utilizing residues at infinity.
Comment: You did not tell us what $C$ is.  In particular are $a,b$ inside, outside, on that contour?
Comment: $C$ is just any closed curve encompassing the whole branch cut.
Comment: Of course that must be included in the question, not just mentioned in a comment.
Answer: More complete version of Pedrpan's answer...  As $z \to \infty$, we have
$$
\frac{z-a}{z-b} = \frac{1-a/z}{1-b/z} =
\left(1-\frac{a}{z}\right)\left(1+\frac{b}{z}+O(z^{-2})\right)
= 1 +\frac{b-a}{z}+O(z^{-2})
$$
then one branch of the square root is analytic near $z=\infty$ and
$$
\left(\frac{z-a}{z-b}\right)^{1/2} = 1 +\frac{b-a}{2z}+O(z^{-2})
$$
We chose the branch of the square root so that the integrand $ \to 1$ at $z=\infty$.
The residue at $z=\infty$ is $\frac{b-a}{2}$ so the integral is
$$
2\pi i \frac{b-a}{2} = i\pi(b-a) .
$$
Comment: Thank you for elaborating on the other solution. Someone commented before that you could not use Cauchy's integral theorem because of analytic continuation problems. The comment is deleted now, but it would be really helpful for me if you could explain why there are no issues with analytic continuation, contrary to that person's claims.
Answer: We have that $$\sqrt{\frac{z-a}{z-b}} = 1 + \frac{b-a}{2}\frac{1}{z} + O\bigg(\frac{1}{z^2}\bigg)$$ therefore using Cauchy's integral formula we have that $$\oint \sqrt{\frac{z-a}{z-b}}dz = 2 \pi i  \frac{b-a}{2} = (b-a)\pi i .$$
Comment: Thanks for answering! Just to clarify, what is the point you are expanding about and what are you using as $x$ for your first step.
Comment: Sorry about that. I changed the $x$'s to $z$'s. Hope that clarifies things.


FlaskApp - Setup VS Code Debugger after install flask-socketio extension

Question: I'm running a flask rest api using vscode as the IDE. I could setup the VSCode launcher in order to debug the application.
launch.json
  {
        "name": "Python: Flask",
        "type": "python",
        "request": "launch",
        "module": "flask",
        "env": {
            "FLASK_APP": "wsgi.py",
            "FLASK_ENV": "development",
            "FLASK_DEBUG": "1"
        },
        "args": [
            "run",
            "--host",
            "0.0.0.0",
            "--port",
            "5000",
        ],
        "jinja": false,
        "justMyCode": true
    },

I need to use web sockets, so I've installed flask_socketio and eventlet extensions. To make the app working again I've replaced
if __name__ == '__main__':
    app.run(host="0.0.0.0", port=5000)

by
if __name__ == '__main__':
    socketio.run(app, host="0.0.0.0", port=5000, debug=True, use_reloader=True, log_output=True)

After that, the VS Debugger stopped working.
Do any of you know if it is possible to configure VSCode to continue debugging this app?
Thanks in advance
Answer: To use the VSCode debugger with eventlet or gevent you have to enable the gevent option, as indicated in the documentation.
The option is named after gevent, but should have been named "greenlet" really, as I have found that it also applies to eventlet.


Find row which has unique values with respect to some of its columns

Question: My SQL table is something like this:
id, name, value1, value2, value3, value4
1, xyz, 1, 2, 4, 1
2, xyz, 4, 2, 4, 1
3, abc, 4, 2, 4, 1
4, abc, 4, 2, 2, 1
5, abc, 4, 2, 2, 1

I want to write a Sql query which returns rows which has any of their values (read: value1,value2,value3,value4) changed. So the result output would be:
id, name, value1, value2, value3, value4
1, xyz, 1, 2, 4, 1
2, xyz, 4, 2, 4, 1
4, abc, 4, 2, 2, 1

I understand, if I just needed values in output I could have used Distinct or Group by like:
select distinct value1,value2,value3,value4 from table;

But, here I need id and name columns too in output.
Wondering if I really need to write a subquery or create virtual/inner table to get my result. Or, there is a smarter way?
My question is not similar to How to find out whether a table has some unique columns. Let me know if you think otherwise, I can clarify.
Comment: Why the row with the id = 2 is not on your result set?, it changed from the previous one
Comment: I was about to answer but why is 5 expected in the result, it's a change to 3. 1 and 3 would make sense as they were changed. 2,4,5 would as they are changes. 2 and 4 would as 5 didn't change 4. 1,3,5 though, I'm missing something.
Comment: What does "changed" mean to you?
Comment: from older value in other row. the table is sorted on id coloumn
Comment: So changed from the previous row based on id?
Comment: because I want only one row for a given value1, value2, value3, value4.
Comment: @S.Singh Then why did you choose row 3 instead of 2? or 5 instead of 4?. Can you clarify your criteria?. We can't just guess what you want
Comment: I am updating the result output to clarify.
Comment: I want only one row for change in value1,value2,value3,value4. And it would be nice to get very first row where the change is detected. (thanks for asking questions). Let me know if the udpated output is not clear.
Answer: Try this
SQL FIDDLE EXAMPLE
select *
from table
where id in (select min(id) from temp group by value1,value2,value3,value4)

Comment: Thanks for answer!
This is what I needed, short and simple.
Answer: Well, for your updated question, I believe that you can do it like this:
;WITH CTE AS
(
    SELECT  *,
            RN = ROW_NUMBER() OVER(PARTITION BY value1, value2, value3, value4 ORDER BY ID)
    FROM YourTable
)
SELECT id, name, value1, value2, value3, value4
FROM CTE
WHERE RN = 1;


Cant connect Jetpack to wordpress.com

Question: I have installed the jetpack plugin but I cant connect it to my website. When I
click the connect button, nothing happens. My browser tries to load but nothing happens.At the end it shows an error like this:
cURL error 28: Operation timed out after 60002 milliseconds with 0 bytes received

What should I do about that?
Answer: I was having the same error (among others like HTTP[403]). Make sure to deactivate all other plugins, there is a known list of known conflicting plugins: https://jetpack.com/support/getting-started-with-jetpack/known-issues/ (Including typical ones like iThemes security, W3 Total cache, WP All Export )
If you use a CDN or Cloudflare it may be worthwhile checking out that help article: http://support.cloudflare.com/hc/en-us/articles/218377098-WordPress-JetPack-and-CloudFlare
Also it seems that for some deactivating, uninstalling, and reinstalling Jetpack helps.
Also check your XMLRPC file. You can do this by going to your web site URL and adding "/xmlrpc.php" to the end (without the quotes). When it loads in your browser, you should see "XML-RPC server accepts POST requests only." on a line by itself. Common causes for this, again, are plugins or themes conflicting.
I had tried all of the above and the final thing to let it connect was php.ini configuration changes. Beyond the typical ones like increasing memory:
    memory_limit = 512M
    upload_max_filesize = 100M
    post_max_size = 512M
    max_execution_time = 300
    max_input_time = 300

... this was the one to fix it:
        output_buffering = 2048
I was using HostGator but I have a feeling other shared hosting environments like GoDaddy may have the same issue.
I wrote an article going through all the steps I took beyond that ( http://www.gordowebdesign.com/wordpress-troubleshooting-jetpack-failed-connection-curl-error-28-operation-timed-out-after-1000-milliseconds-with-0-bytes-received-solved/ ). Deactivate all other plugins before going further, and check that list. One of them is most likely the culprit.
Also it is worthwhile to run the debugger and check the output for helpful information:
http://yourdomain.com/wp-admin/admin.php?page=jetpack-debugger
or visit http://jetpack.com/support/debug/ and add your URL.
If this doesnt work make sure to enable define('JETPACK_DEV_DEBUG', true); in your wp-config.php
(Need more reputation to post those as links, sorry)
Answer: if you hosting wordpress on your own computer, and if you run PHP as FastCGI, please check if system environment variable PHP_FCGI_CHILDREN is set to value more than 1.
Reason for that is following: when you click "connect", plugin is storing security tokens into your database, then Wnotifies www.wordpress.com and WAITS [to cleanup security tokens when validation is over]. which validates security tokens by making request to your wordpress site -- this should use another instance of PHP FastCGI [remember, first one is WAITING, and you need another one to respond].
Fix is: set system environment variable PHP_FCGI_CHILDREN=8 (or at least 2), then restart PHP FastCGI service or process [depending on how you run it]. -- you may want to check if FastCGI processes were started. then try to connect again.

Cant connect Jetpack to wordpress.com


Interpret a model in R and find a connection with a statement

Question: I would appreciate help with how to find a connection between a statement and a summary() function on linear regression model in R.
I have created a model for simple linear regression in Rstudio over data that contains data on the deviation of the earth's average temperature during the period 1970–2007 and when using summary() to this I get the following:

And I would now like to find the connection between this model and the following statement "The greenhouse effect is not a problem, there is no proven trend towards a warmer climate". But how should I interpret the information provided by the model?
The exact question is as follows: What is the link between the statement and the model that was adapted to the same time period? It is also said that this link will lead me to which test I should use to conduct a hypothesis test on this.
My thoughts: Pr(>|t|) from what I understand gives us the p-value for two-sided testing of the null-hypotheses that no difference / change occurs (i.e. $\alpha=0$ and $\beta=0$) and since this is incredibly small, the null hypothesis should be rejected, but that is a contradiction to the statement and not a connection? And also, how can the intercept be -33 and what does this mean?
Answer: I am not sure what you mean with "connection".
The t-test tells you the probability of observing a coefficient for year as extreme as 0.017 under the assumption that the true beta is 0. As the probability is extremely small, we can conclude that the true beta is not 0 and therefore there is a true increase in temperature described by year.
The coefficient of year tells you the estimated change of Y given a unit change in year.
Comment: Thanks for the clear answer! I now understand a little bit more and can also draw the conclusion that the statement is wrong.
Comment: The exact question is "What is the link between the statement and the model that was adapted to the same time period?" with the time period being the year 1970-2007. And like you, I also interpreted it as that there is a true increase in temperature, but got a little confused since contradicts the statement and is not a link.
Comment: Well, the statement is simply wrong?
Comment: Ok thank you! But what is the meaning of the intercept being -33? Maybe that has something to do with the link
Comment: @user346623 not at all. The intercept is simply the estimate of ```Y``` when ```year = 0```. That is of course meaningless with the data you are using as there is no linear temperature increase from year 0 to year 2007. You can instead get a meaningful intercept if you replace the actual values of year with values of 0,1,2,3 ... then your intercept will be the estimated temperature at year 0, which is in your case 1970. The slope will remain the same.


How can I solve $1/x = \ln x$?

Question: Another way to look at it is  $x^x  =  e$.
It seems possible, but I really don't know.  It seems very helpful to know the exact value where a function's y value is the same as its slope.
Comment: You can't. $\qquad$
Comment: You can find many duplicates of that question on MSE! Also you can use https://approach0.xyz/search/ to find that.
Comment: There are several (actually infinitely many) complex solutions to the equation, but there is only one real solution, written as $x=e^{\operatorname{W}(1)}$, where $\operatorname{W}(z)$ is the Product Log Function. Here's a link to more info on this function: http://mathworld.wolfram.com/LambertW-Function.html
Comment: @Robert Kaman in that case just search for an answer and delete that one. If you are interested to discuss or clarify some particular point you can raise that here.
Comment: @Robert Kaman $x^x = e$ has only one real solution around $x = 1.763$
Comment: @clathratus this should be the answer, not a comment. Go for it!
Comment: @LarryB ok... if you insist.
Comment: IMO, knowing where a function equals its slope is anecdotal and of little practical use. On the opposite, the function that equals is slope *everywhere* (more generally a fixed multiple of the slope) is of a fundamental importance in calculus and applications of the dynamics of linear systems.
Comment: but you can find a sequence that tends to the zero of $xln(x)-1$ by using Newton or Secant method
Answer: Per the comment of clathratus, the Lambert W function is relevant here; since $x\ln x=1$, take $x=1/W(1)$ for some branch $W$ of the function. However, if you actually want a few decimal places of $x$ in a hurry, numerical methods such as the Newton-Raphson method are prudent. Define $f(x):=x\ln x-1$ so $f'=\ln x+1$ and $g(x):=x-\frac{f(x)}{f'(x)}=\frac{x+1}{\ln x+1}$; then we can use the recursion $x_{n+1}=g(x_n)$ (which is probably what ab123 did), provided we choose a sensible seed. The choice $x_0$ should do.
Answer: green line is a $y=e$ and blue line is graphic for function $x^x$
Answer: There are several (actually infinitely many) complex solutions to the equation, but there is only one real solution, written as $x=e^{\operatorname{W}(1)}$, where $\operatorname{W}(z)$ is the Product Log Function. Here's a link to more info on this function: http://mathworld.wolfram.com/LambertW-Function.html
Answer: Hint:
Use the iteration method as follow
$$x_{i+1}=e^{\frac{1}{x_{i}}}$$
start with $x_0=1$
After $40$ iterations the value of $x$ will be $1.763222834$
Answer: You may also use numerical integration: the wanted solution is $\frac{1}{W(1)}$ with $W$ being Lambert's function, hence by the Lagrange inversion theorem
$$ x = \left[\left(\int_{-\infty}^{+\infty}\frac{dt}{\pi^2+(e^t-t)^2}\right)^{-1}-1\right]^{-1}. $$
The integrand function behaves like the normal distribution close to the origin, like the Laplace distribution over $t\gg 0$ and like the Cauchy distribution over $t\ll 0$. This leads to $x\approx 1.76322$.
Answer: This can be solved either by using Lambert W function or Newton Raphson method.
The above equation can be written as -> 1 = x*ln(x)
1. (Using Lambert W function):
W(x*ln(x)) = W(1)     ---- [1]
as per Lambert W function: W(x*ln(y)) = ln(y)
hence,
ln(x) = W(1)    {substituting in [1]}
so,
x = e^(W(1))
but W(1) is approximately equal 0.56714329
refer: https://en.wikipedia.org/wiki/Lambert_W_function;
substituting the value (W(1)) above:
x = 1.76322 (approximate value)
2. (Newton Raphson Method):
consider f(x) = x*ln(x) - 1 & solve further using Newton Raphson Method formula for different values of x, starting with 0.
https://en.wikipedia.org/wiki/Newton%27s_method
Hope this helps!

How can I solve $1/x = \ln x$?


Inserir valor na Tabela Y para todas ID existente da Tabela X

Question: Eu tenho uma tabela chamada CONTAS com uma coluna account_id.

Tenho outra tabela chamada PREMIO com colunas account_id, id_premio e itemqtd

Eu queria um comando onde eu inseri-se o id_premio e itemqtd mas para a coluna chamada account_id ele inserir todas account_id da tabela CONTAS pois quero dar o mesmo Premio e quantidade para todas as contas registradas até aquele momento.
Answer: Isso aqui deve resolver o seu problema
insert into premio(contas_id, id_premio, qtd_premio)
select contas_id, 01, 1500 from contas

Explicando: Será feito um select em todos os dados da tabela CONTAS trazendo o campo contas_id, o código do prêmio (01) e a quantidade do prêmio (1500) e os mesmo serão incluídos na tabela prêmio.
Modifique os valores exemplos de acordo com sua necessidade.
Obs.: Tome cuidado com as chaves primárias, se o campo id_premio for a chave primária da tabela PREMIO você terá que ver como irá tratar corretamente.
EDITADO
O insert ficaria desta forma
insert into entregador(account_id, id_premio, itemqtd)
select account_id, 1, 13 from login

Comment: Muitíssimo Obrigado cara pela sua atenção  ajuda, funcionou do jeito que eu precisava!
Ps: a primeira tentativa eu digitei um caractere errado e não vi. rs
Comment: Opa obrigado, mas obtive o seguinte erro:
#1054 - Coluna 'contas_id' desconhecida em 'field list'

o nome da coluna está correto e existe na tabela, porém contas_id é chave primaria da tabela CONTAS já id_premio não é chave primaria
Comment: Tem algo estranho então na estrutura que tu passou... Não tem como você editar sua resposta e por uma imagem da estrutura de cada tabela?
Comment: Usei nomes ficticios para poder explicar mas vou passar como está:
Tabela de contas ( chamada login ) - http://prntscr.com/ow8jfa
Tabela premios ( chamada entregador ) - http://prntscr.com/ow8kse
Comment: Verifique a edição da minha resposta, é estranho ocorrer esse erro citado por você se o campo existe...
Answer: select CONTAS_ID into PREMIO from CONTAS

Quando usamos INTO jogamos todos resultados para a tabela informada.
Comment: ele retorna um erro LIMIT 0, 25 e nessa linha onde coloco  ( ID_PREMIO ) e ( QTD_PREMIO )  numérico tipo 444 e 1


Is there a contradiction in these two definitions of limit Superior?

Question: Definition 1 : Let $A=\{a_n\}$ be a sequence of real numbers not necessarily bounded . Then we define :
$\lim \sup ~ a_n = \inf ~\{\sup ~a_n,~\sup ~a_{n+1}~\sup ~a_{n+2}, \cdots\} $
Definition 2 : If $A =\{a_n\}$ is a sequence of real numbers which is bounded above, then the limit superior of $A$ denoted by $S$ is the infimum of those real numbers $v$ with the property that there are only a finite number of natural numbers $n$ such that $v < a_n$
Please consider this image :
Let the sequence $A$ denoted on the number line  be bounded above by $b$ and may or may not be bounded below. ( In this case, we have taken $A$ to be bounded below by $a$ as well)
Now, $\{\sup ~a_n,~\sup ~a_{n+1}~\sup ~a_{n+2}, \cdots\}$ is a monotonically decreasing and bounded sequence which converges to the point $S . S_o =~ \sup ~a_n , S_1 = ~\sup ~a_{n+1}$ and so on.
Question 1: As per definition $2$, there can only be a finite numbers of terms to the right of $S$. But how can this be possible here when we have a whole sequence of supremums itself convering towards $S$.
Question 2: What could happen when $A$ is not bounded below? I fail to understand how can only a finite number of terms be there on the right side of $S$.
Thank you for help.
Comment: What exactly do you mean by $\sup a_n$?
Comment: The way you have written it, definition 1 does not make sense. The notation $\sup\{a_n, a_{n+1},\dots\}$ means supremum of all terms of the sequence starting with $a_n$. If you want to write $\{\sup a_n,\sup a_{n+1},\dots\}$, then $a_n$ has to be a set, not a number.
Comment: Another problem with your definition 1 is that you need to take infimum from a set of numbers. You probably wanted to write something like $\inf_{n\in\mathbb N} \sup\{a_k; k\ge n\}$, which is another way of writing $\inf \{\sup\{a_k; k\ge n\}; n\in\mathbb N\}$
Comment: The infimum of a set need not belong to the set. For every $T > S$, there are only finitely many $n$ such that $a_n > T$.
Comment: that means, $S$ need not belong to $A$ .. but still, there can be infinite elements greater than $T$ ?
Answer: I hope that this makes things clear for you.
Let $A$ denote a sequence $\left(a_{n}\right)$.
Definition 1a) $\limsup A:=\lim_{n\rightarrow\infty}s_{n}$ where
$s_{n}:=\sup\left\{ a_{k}\mid k\geq n\right\} $
The fact that sequence $\left(s_{n}\right)$ is non-increasing makes
it possible to define equivalently:
Definition 1b) $\limsup A:=\inf\left\{ s_{n}\mid n\in\mathbb{N}\right\} $.
Now define $V:=\left\{ v\in\mathbb{R}\mid\text{the set }\left\{ n\in\mathbb{N}\mid v<a_{n}\right\} \text{ is finite}\right\} $
and note:
$$v\in V\iff\exists n\; s_{n}\leq v$$
This shows that $V=\cup_{n=1}\left[s_{n},\infty\right)$ and consequently
$\inf V=\inf\left\{ s_{n}\mid n\in\mathbb{N}\right\} =\limsup A$

In special case where $A$ is not bounded above we have $s_n=+\infty$ for each $n$ so that $\limsup A=+\infty$. Secondly we have $V=\emptyset$ and $\inf\emptyset:=+\infty$. So everything remains valid in that case.


Strange CardView issue: ("Failed to find: com.android.support:cardview-v7:21.0.+" Error)

Question: I have Android 5.0 and the most current version of the Android Support Libraries (21.0.2). I am trying to access the CardView and the RecyclerViews in Android. When I add:
compile 'com.android.support:cardview-v7:21.0.+'
compile 'com.android.support:recyclerview-v7:21.0.+'

to the app's build.gradle dependecies, I get the errors:
Failed to find: com.android.support:cardview-v7:21.0.+

and
Failed to find: com.android.support:recyclerview-v7:21.0.+

I'm not sure why this is. This is the only way I have seen people do it (and it's the way suggested on Google's website here). After this, I cannot make CardViews or RecyclerViews in my project.
I have also checked my android sdk folder:
C: > ... > android-sdk > extras > android > support > v7

and both the 'cardview' and 'recyclerview' directories are there with all the files in them.
I'm not sure why this is so...
If you have any questions please ask and any suggestions or answers would be greatly appreciated!
Comment: did you using gradle?
Comment: Yes I'm using gradle and I'm putting it in the build.gradle
Comment: so you need to add these things in your dependency if you have not done already
Comment: Yeah, their in my dependencies already...
Answer:
and both the 'cardview' and 'recyclerview' directories are there with all the files in them.

Those are for Eclipse.
You need to install the "Android Support Repository" in your SDK Manager:

That should enable Gradle for Android to find those artifacts.
Answer: I just had to put correct lib version. i.e. change:
compile 'com.android.support:cardview-v7:21.0' to
compile 'com.android.support:cardview-v7:21.0.2'


Three20 TTWebController ignores supported url schemes registered by app in TTURLMap

Question: We are using TTWebController to display web pages served by our server.  I would like these pages to include urls to be handled by the iphone app.  Eg:
page.html:
Show Profile On Phone"

AppDelegate.m
TTUrlMap* map= navigator.URLMap;
[map from:@"*" toViewcontroller:[TTWebController class]];
[map from:@"myapp://profile" toViewcontroller:[ProfileController class]];

When the page displays on the phone in the TTWebController, clicking the link doesn't display the ProfileController, nothing happens.  I would expect TTWebController to recognize that the scheme is registered, run the normal TTNavigator magic and show the associated controller.  Is there a way to do this?
Note: registering the URL scheme with the app itself doesn't work either, ie. TTWebController doesn't recognize the url and call:
[[UIApplication sharedApplication] openURL:url]

Any ideas?
Answer: It looks like TTWebController registers itself as the UIWebViewDelegate of the UIWebView, so you can override -[UIWebViewDelegate webView:shouldStartLoadWithRequest:navigationType:] -- e.g. if your URLs all start with myapp:, then you could do this:
- (BOOL)webView:(UIWebView *)webView
  shouldStartLoadWithRequest:(NSURLRequest *)request
  navigationType:(UIWebViewNavigationType)navigationType
{
  if (navigationType == UIWebViewNavigationTypeLinkClicked &&
      [request.URL.scheme isEqualToString:@"myapp"])
  {
    // This is our private URL
    TTOpenURL([request.URL absoluteString]);
    return NO;
  }
  else
  {
    return [super webView:webView
                  shouldStartLoadWithRequest:request
                  navigationType:navigationType];
  }
}


Prove that set of all lines in the plane is uncountable.

Question:
Let $L$ be the set of all lines in the plane. Prove that $L$ is uncountable, but only countably many of the lines in $L$ contain more than one rational point.

Attempt: Well, I was trying to define $L$ using linear combinations of points since a line is a linear combo of two points. So, I wanted to define $L=\{ax+yb:x+y+z=k,k∈Z_+\}$. But, this does not seem right. Anyway, once I define $L$ I would try to find a function from $L$ to some uncountable set D that is onto or a function from D to L that is 1-1. Help appreciated thank you.
Comment: @Chiruno "if a line contains two rational points then every point on the line is also rational" obviously not.
Comment: @Koba Actually say something about what you have tried. Saying "I have little idea where to start" is useless.
Comment: Think of how many points you need to uniquely define/specify a line in the plane.
Comment: You can find a function, e.g., using the coefficients $a,b$, since for every pair of coefficients, you get a line.
Comment: @Koba: Right, and each line containing two or more rational points is determined by two of those rational points, so there are only ...
Comment: @Koba: That's right: that argument shows that there are only countably many lines that contain more than one rational point.
Comment: @Koba : I'm sorry if my comment seemed condescending.  Maybe I should have written "obvious" rather than "trivial".  The set of all vertical lines has the same cardinality as the set of all real numbers, and you probably already know the real numbers are an uncountable set.  So the set of _all_ lines in the plane has to be uncountable.  The problem is not that the question in the title is "trivial", but that the title does not really match the question.
Comment: There are at least as many distinct lines as there are real numbers. Now if a line contains two rational points then every point on the line is also rational.
Comment: Ah crap, forget that. I was mixing myself up with linear combinations. To redeem my previous blunder, a line with two rational points will intersect the x-y axis at a rational point.
Comment: For the second part, You could use a combination of the theorem that the rationals are countable and then use [Cantor's Pairing Function](http://en.wikipedia.org/wiki/Cantor_pairing_function#Cantor_pairing_function) or a variant of it.
Comment: @AndresCaicedo Well, I was trying to define $L$ using linear combinations of points since a line is a linear combo of two points. So, I wanted to define $L=\{ax+yb: x+y+z=k, k \in Z_+\}$. But, this does not seem right. Anyway, once I define $L$ I would try to find a function from $L$ to some uncountable set $D$ that is onto or a function from $D$ to $L$ that is 1-1 .
Comment: @user99680 good point, but I want to make sure I define $L$ properly which I have a hard time with.
Comment: For the second question: how many pairs of rational points are there?
Comment: @BrianM.Scott infinitely many I am guessing.
Comment: Certainly infinitely many, but what *kind* of infinite?
Comment: @Brian M. Scott: the "A lot"type of infinite? Just kidding, but there is the fact that the lines overlap.
Comment: @user99680: One of the two types named in the question.
Comment: @Brian M Scott: I was just kidding; please see my post above your previous.
Comment: @BrianM.Scott countably infinite, i.e. the set of all pairs of rational points is denumerable.
Comment: @BrianM.Scott n pairs of rational points, $n\in N$? Sorry, for being too dense.
Comment: @Koba: There may be more than one pair of points per line, but that doesn't hurt. Each pair of rational points determines exactly one of the lines that contain two or more rational points, and there are only countably many pairs of rational points, so ...
Comment: @BrianM.Scott there are countably many lines!!!
Comment: @Koba : the question in your title is trivial.  For the benefit of future readers, could you please alter the title to match your actual question better?
Comment: @StefanSmith ok. I did not know it is trivial though.
Answer: You can List all lines in the plane this way:
Use the fact that a line is described uniquely once you know its slope, and one of its
intercepts with the axes. The slope is indexed by the Reals, and so is the intercept, say the x-intercept. So we count all the possible pairs ( slope, x-intercept), and show
it is equal to $|\mathbb R|$
1) Consider all lines thru the origin $(0,0)$.  These are described uniquely by their
slope, and there are $|\mathbb R|$ of them, since the slope is parametrized by the Reals.
2) From 1) , we can cover all other cases of lines not going thru $(0,0)$ , by considering all possible ( say x-) intercepts of a line thru any point, with fixed slope$m$. For every line
in 1), there are $\mathbb R$ lines not going thru the origin, but with the same slope.
This means there are $|\mathbb R|\times |\mathbb R|=|\mathbb R|$ total lines in the plane.
Comment: You forget all the lines with "infinite" slope; lines perpendicular to the x-axis.
Comment: That doesn't affect the cardinality in the end; you're just adding one line.
Comment: I am adding an uncountable infinity of lines, which you neglected. That is significantly more than "one line."
Comment: No, I meant one line at each interval. And I did include the horizontal line in the count. Still, even considering your description,if you have $|\mathbb R|$ lines at each point, throwing-in the horizontal line does not affect the cardinality of the collection; you still have $\mathbb R$ lines; just include that line, and the cardinality. The collection of all finite $m$ union an additional line And you're not including uncountably-many, there is just one for every interval $[n,n+1]$. So I do not see how my calculations are incorrect.
Comment: If you had just asked, I would have clarified the fact that I am including the horizontal line in my count. Basically, I am including the possibility of $m=\infty$ in my count. It is your unwarranted assumption that leads you to believe I am undercounting. And you may want to make your own argument more rigorous.
Comment: (Cont.) if you believe mine is not rigorous-enough. Besides, the question is about giving an accurate "count" (cardinality), not that of giving an accurate description of the set.
Comment: An accurate description of the set will allow an accurate proof of cardinality; and you are entering a pissing match over whose answer is better. Comments are for critiquing answers to a question.
Comment: What pissing match? you made unwarranted assumptions (which are false in this case) over my post, instead of asking. So I'm just replying in kind.
Comment: unwarranted assumptions in this case are probably me misunderstanding your answer and I concede your point, partially because I tire of this discourse. Good day.
Comment: Just a quick thing: if you could please address these issues shortly after the answer is posted; it is easier to address them under these conditions.Of course, if you believe there is something incorrect, no problem bringing things up at any point. Peace.
Answer: All lines in the plane are a superset of all lines perpendicular to a given line.
How is it with perpendicular lines, points on their parent line and the number of points on a line?
Comment: What do you mean by " How is it with perpendicular lines, ...", that is too much hand-waving.
Comment: If you believe my argument lacks rigor, you may want to make your own argument more rigorous.
Comment: @user99680 This is obviously a homework question. I am not going to do this gentleperson's homework for them. Besides, my answer goes at presenting a partial answer from a strategy independent of the orientation of the plane, and indeed independent of linear equations in the plane. This is elementary set theory, not analysis.
Comment: The reason I brought it up is because you seemed to be saying my answer was not rigorous-enough.
Comment: @user99680 and that is for you to take to the comment thread of your own answer.
Comment: I did bring it up there.
Answer: How about this? Let L be a line in the plane and v some vector that does not generates that line. You can prove that for every pair of real numbers (a,b), L+bv and L+av have empty intersection. For the second part, try this idea:
Every line with a irrational slope contains only one rational point (prove it by contradiction).


Preciso de ajuda para criar duas tabelas com estrutura de decisão em PHP

Question: Criar uma aplicação em PHP que verifique palavra por palavra do array abaixo se o total de letras é impar ou par.
Para mostrar o resultado. montar uma página HTML básica com duas tabelas: Uma com as palavras de total de letras ímpares e outra com o total de letras pares, seguida do total das letras.
$valores = [ 'estudar', 'educação', 'esforço', 'persistência',
             'dedicação', 'crescimento', 'evolução', 'sabedoria',
             'trabalho', 'entusiasmo', 'alegria', 'vitoria',
             'sucesso', 'profissão', 'conhecimento', 'vida' ];

Comment: Esta pergunta parece ser descontextualizada porque parece ser sobre um exercício de lógica o qual não demonstrou ter havido esforço por parte do autor dada a ausência de uma implementação preliminar.
Comment: Isso não é uma dúvida, isso é um enunciado. Tente começar o seu trabalho, conforme as dúvidas forem aparecendo você pode criar perguntas aqui no site para então podermos te ajudar. Aproveita e faça um [tour] pelo site e veja o guia [ask].
Comment: Já tentou fazer alguma coisa, se sim, que tal postar o que tentou e se deu algum erro dai sim pode ter uma ajuda mais assertiva.
Answer: O primeiro passo é pegar o tamanho da palavra com a função mb_strlen, feito isso verifique se o tamanho da palavra retorna ou não o resto da divisão($tamanho % 2 == 0).
Agora defina um array com a seguinte estrutura:
$resultado = array('impares' => '', 'total_impares' => 0, 'pares' => '', 'total_pares' => 0);

Caso o resto da divisão seja zero então ele é par, adicione essa palavra na chave $resultado['pares'] e incremente o contador dos pares `$resultado['total_pares'], se o resto for um faça o mesmo processo so que dessa vez nas impares.
Com array formatado, faça dois foreach() nas tabelas.
Obs: outra forma de calcular o total seria usar count nas chaves impares/pares e atribuir o valor em total_impar/par após o foreach que faz a 'separação'
Answer: Apesar disso ser um exercício de lógica o qual, até o presente momento, aparentemente não teve esforço por parte do autor demonstrado, gostaria de deixar minha contribuição mesmo assim.
A solução é tão simples que, à parte do array de entrada, resolve-se com apenas duas linhas:
$words = [ 'estudar', 'educação', 'esforço', 'persistência',
           'dedicação', 'crescimento', 'evolução', 'sabedoria',
           'trabalho', 'entusiasmo', 'alegria', 'vitoria',
           'sucesso', 'profissão', 'conhecimento', 'vida' ];

$odd = array_filter( $words, function( $word ) { return ( strlen( $word ) % 2 == 0 ); } );

$even = array_diff( $words, $odd );

Os arrays $odd e $even resultantes contém, respectivamente:
array (size=8)
  1 => string 'educação' (length=10)
  2 => string 'esforço' (length=8)
  6 => string 'evolução' (length=10)
  8 => string 'trabalho' (length=8)
  9 => string 'entusiasmo' (length=10)
  13 => string 'profissão' (length=10)
  14 => string 'conhecimento' (length=12)
  15 => string 'vida' (length=4)

array (size=8)
  0 => string 'estudar' (length=7)
  3 => string 'persistência' (length=13)
  4 => string 'dedicação' (length=11)
  5 => string 'crescimento' (length=11)
  7 => string 'sabedoria' (length=9)
  10 => string 'alegria' (length=7)
  11 => string 'vitoria' (length=7)
  12 => string 'sucesso' (length=7)

Ao contrário da indicação do amigo @perdeu, usar mb_strlen(), nesse caso, resulta em falsos-positivos pois faz com os acentos das palavras sejam considerados como comprimentos adicionais.
Leituras recomendada:

strlen()
mb_strlen()
array_filter()
array_diff()
Comment: +1 pela resposta mais eleborada. Obrigado pela correção tbm. Fiz um teste [aqui](http://phpfiddle.org/main/code/6hvk-x0g9) com o `strlen` a palavra `aça` ele cai na categoria dos pares, quando vc usa `mb_strlen` e passa o encondig da string ele cai nos impares como esperado.
Comment: Até hoje eu não tenho bem certeza da usabilidade de mb_strlen().


Rules help: After updating existing content

Question: First time using Rules to make a complicated rule. Would appreciate some help. I'm making rules to send an e-mail, to a pre-defined e-mail address, after an existing node is updated. This node is of a certain type, and this type has a taxonomy term reference field. When any node of this type gets updated, by a user with certain role, Drupal should send an e-mail, and in the e-mail it should attach the name of the taxonomy term.
tl;dr/problem: What I'm having trouble is, when creating a condition to check the user's role (the user who updated the content, not the author). There seems to be only the "Author" of the node available on the Data selector (see attached image). Is node:author the correct one to check for the user who updated the content?
Comment: Yes, it is `site:current-user`. Everything is OK with multiple logged in users.
Comment: There seems to be a "site:current-user" selector as well. Is this the correct one? I'm not sure how reliable this is when multiple users are logged in to the system?
Answer: For your task you need site:current-user token which corresponds to $GLOBALS['user'] (global $user) object.

I'm not sure how reliable this is when multiple users are logged in to the system?

Webserver creates new PHP thread (or process) for each request so there are no sharing variables between requests.global $user variable is initialized by Drupal on every request.
When you have just updated a node you can use global $user to know who updated this node. At any time after updating you can get that user id from revision ($node->revision_uid).


Updating modules with drush without breaking SVN?

Question: Right, this has been breaking me for two days. I can't get an answer anywhere!
I have drush 4.4 on my server. I am using SVN via Unfuddle.com. I have a site, I want to update a lot of modules. I want to update just the code, then check it's working (DB updates are not a concern at this point) then commit the relevant code.
It used to be that drush dl  would simply download the module code over the top of the old module, without removing it. That is no longer the case. Now, AFAICT, drush removes the module directory and replaces it with the newer version. That's all well and good, because it solves the problem of old files that are no longer in the updated module being left behind.
However, using the drush dl or upc commands, I am stuck, because running these commands does indeed get the newer version, but it destroys the SVN data folder in the process, leaving me with "! module/file.php" problems everywhere for files that aren't there any more.
I have been advised that "drush upc/dl modulename --version-control=svn" should work, but it doesn't. The SVN data is still destroyed.
This leaves me with the potential nightmare of having to:
svn del module,
svn commit -m"Removed module",
drush dl module,
(test the module),
svn add module,
svn commit -m"Added module" -
for every single module, which is a total horror.
I do not want to set up drush to auto-commit my changes, I just want to download them and commit them all manually at the end when I'm happy with the changes. This can't be that hard, but I simply cannot get it to work.
I have also been advised that moving to git (yes, I'm aware unfuddle supports git!) is also a solution, but it's not an immediate one, and is not satisfactory at this point in time.
Can anyone please shed some light on this?!
Comment: Might be easier to learn git.
Answer:
because running these commands does indeed get the newer version, but it destroys the SVN data folder in the process, leaving me with "! module/file.php"

I'm running Drush 4.4 and this does not appear to be the case for me. Running drush upc or drush up keeps your .svn directories intact. You can svn status to review the changes to the modules. New files are indicated by ? and removed files are indicated by !.
Test your site's functionality. Once you are satisfied that the modules are still working correctly, you can then svn add/remove with a snippet such as the following:
add:
svn status | grep '^\?' | cut -c8- | while read f; do svn add "$f"; done

remove:
svn status | grep '^\!' | cut -c8- | while read f; do svn rm "$f"; done

Comment: Perhaps "destroys svn data" was an error on my part - previously, I didn't see any ! but just ?, which I duly svn added. This is perhaps a point of ignorance on my part. I suppose it was expectation of the ease of the previous manner in which I worked, which was (due to something now fixed in drush) actually erroneous.
Answer: You should add --svnsync to your command.
Example :
 drush pm-update module_to_update --version-control=svn --svnsync


DataFrame Python

Question: Boa Tarde galera, estou com uma dúvida e queria pedir a ajuda de vocês. Queria saber como fazer um DataFrame em python que armazene os dados de uma view do sql e também saber como ficaria a sintaxe, obrigado.
Obs: já fiz a conexão com o banco de dados.
Aqui faço a conexão com o banco de dados, ai queria jogar a minha view dentro de uma data frame.
import pyodbc
import pandas as pd

#Conexão com Sql Server
connection = pyodbc.connect("DSN=SQLServer")

if connection:
    print ("Conectado ao SQL!\n")

try:
    with connection.cursor() as cursor:
        #Utilizando o fetchal para trazer varios registros
        sql = "SELECT * FROM dw.dbo.vW_Vendas"
        cursor.execute(sql)
        tabela = cursor.fetchall()
        print(tabela)
finally:
    connection.close()

Comment: Ola Ytado seria bom para sua pergunta se você adicionar o código que você fez ate o momento.  Se você estiver falando de `pandas.DataFrame` talvez isso te ajude [pandas.read_sql](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_sql.html#pandas-read-sql)
Comment: Obrigado Vou dar uma olhada, adicionei o código para melhorar a pergunta
Answer: df = pd.read_sql("SELECT * FROM dw.dbo.vW_Vendas", connection)

Comment: Muito Obrigado  deu certinho

DataFrame Python


Relation between Pini di Roma and Rutter Magnificat?

Question: I just noticed that the closing of "Quia fecit mihi magna" from the Magnificat by John Rutter (starting at the "Sanctus") is a near-verbatim citation of a passage from movement 2 of Respighi's "Pini di Roma" ("Pini presso una catacomba"). I was just wondering, did Rutter quote Respighi directly, or are they both referencing the same melody which might be even older than that (e.g. some plainchant or anything like that)? Thanks for any insight!
Answer: I don't have scores in front of me, but I did find something interesting while cross-referencing some Wikipedia articles.
Regarding the Rutter:

The movement is closed by a chant-like accompanied Sanctus, taken from the Missa cum jubilo. (source)

And regarding the Respighi:

A hymn is heard (specifically the Kyrie ad libitum 1, Clemens Rector; and the Sanctus from Mass IX, Cum jubilo), the sound rising and sinking again into some sort of catacomb, the subterranean cavern in which the dead are immured. (source)

The following excerpts show the relation very clearly:

Rutter
Respighi
The Sanctus from the Cum jubilo mass, a mass reserved for Feasts of the Virgin Mary

Nice catch!
Comment: Ugh, I could have just looked it up on Wikipedia? Now I feel stupid, that thought really never into my mind somehow. Thanks for doing it for me and for your accurate and detailed answer!


Prove there is no closed-form solution to equations with e^x and x

Question: I have the equation
$$\frac{b}{x}+\frac{ae^x}{1-e^x}=0$$
How do I prove this equation has no closed-form solution for $x$?
Edit: please note $a,b>0$
Comment: Simplifies to $e^{-x}+\frac{a}{b}x-1=0$; therefore are you assuming that $\frac{a}{b}$ be  a non-zero constant?
Comment: Yeah sorry I should have mentioned, $a,b>0$
Comment: Mobeus Zoom, does your post then actually not explicitly and directly say that $\frac a b$ is a non-zero constant and hence $b=ka$ in answer below is actually relying on deduction made explicitly so far only in @JamesArathoon's comment?
Answer: I suppose that you mean no closed-form solution in terms of elementary functions.
Let $b=k a$ which makes the equation to be
$$k+(x-k)e^x=0$$ Now, let $x=k+y$  to make $$y e^{k+y}+k=0 \implies y e^y=-ke^{-k}$$ and the solution is
$$y=W_{-1}\left(-ke^{-k} \right)$$ where appears the lower branch of Lambert function. In the real domain, this function is defined for $0 < k \leq 1$.
Back to $(x,a,b)$ this gives
$$x=\frac{b}{a}+W_{-1}\left(-\frac{b }{a}e^{-\frac{b}{a}}\right)$$
Comment: So how do you show there is no closed-form solution in terms of elementary functions?
Comment: @JairTaylor. This is the big question, I fully agree ! Cheers
Comment: Thanks. I guess one could go from here and bring in the proof that Lambert W doesn't have a closed-form solution in elementary functions, even though this may not be a proof of the overall lemma.
Comment: The other thing I'm wondering is, what if $b>a$ (so that $b/a<1$ is not true and the Lambert W isn't defined for our domain)?
Answer: My answer is for solutions in terms of elementary functions.
$$\frac{b}{x}+\frac{ae^x}{1-e^x}=0$$
$$axe^x-be^x+b=0\tag{1}$$
The left-hand side of equation (1) is an expression of both $x$ and $e^x$, algebraic over $\mathbb{C}$. It can be shown that such expressions don't have elementary inverses:
How can we show that $A(z,e^z)$ and $A(\ln (z),z)$ have no elementary inverse?
For $a,b\in\overline{\mathbb{Q}}$, equation (1) is an algebraic equation of both $x$ and $e^x$. Lin (1983) proved, assuming Schanuel's conjecture ist true, that such equations, if irreducible, don't have solutions in the elementary numbers.


Rotate one 3D coordinate system to another

Question: I have a set of points in one coordinate system and I want to rotate them to another coordinate system in Python. Based on this answer I wrote the following Python function:
<code>def change_of_basis(points, initial, final):
    '''
    rotate points/vectors in a 3D coordinate system to a new coordinate system

        input: m x 3 array of points or vectors that have to be transformed from the initial to the final csys
        initial: sequence of sequences of floats representing the normalized axis of the csys that has to be transformed
        final: sequence of sequences of floats representing the normalized axis of the csys to which has to be transformed

        return: the points/vectors in the new coordinate system
    '''
    x1, y1, z1 = initial
    x2, y2, z2 = final

    M11, M12, M13 = np.dot(x1, x2), np.dot(x1, y2), np.dot(x1, z2)
    M21, M22, M23 = np.dot(y1, x2), np.dot(y1, y2), np.dot(y1, z2)
    M31, M32, M33 = np.dot(z1, x2), np.dot(z1, y2), np.dot(z1, z2)

    # set up rotation matrix
    R = np.array([[M11, M12, M13],
                  [M21, M22, M23],
                  [M31, M32, M33]])

    return np.linalg.inv(R).dot(points)
</code>
Running example:
<code>  initial =  [[ 0.98078528  0.         -0.19509032]
             [-0.19509032  0.         -0.98078528]
             [ 0.          1.          0.        ]]

  final =  [[ 0.83335824 -0.08626633 -0.54595986]
            [-0.55273325 -0.13005679 -0.82314712]
            [ 0.          0.98774564 -0.15607226]]

   new_cys = change_of_basis(initial, initial, final )
</code>
Plotting this gives the result visualized below. The intention is to transform the red/orange coordinate system to the yellow one but the result is the blue coordinate system. Can anyone see what mistake I am making and how to fix this?

EDIT:
It worked to transform the coordinate system. I changed to the function above to what I have now. It allows me to transform the red to the yellow coordinate system. Now what I need is to transform a set of points in the first (red) coordinate system to a set of points in the second (yellow) coordinate system. I thought that this function would work but it does not, is the transformation different for a set of points?
Answer: I'm no expert in linear algebra, but I think your mistake is in not inverting the initial coordinate system.
If A and B are your basis matrices, you are computing A * B, but what you need to compute is A^{-1} * B.
Which makes sense - you multiply by A^{-1} to convert to the standard basis from A, then multiply by B to convert to from the standard basis to B.
Here's another SO answer that talks about implementing this: Change of basis in numpy
EDIT: Peculiar that this version worked for the coordinate system. It's not R you need to invert. You are computing R = A * B, so so by inverting R you get A^{-1} * B^{-1}. You need to invert A first, then multiply.
Comment: I managed to do the transformation using the link you provided. When I tried to apply the rotation to my point cloud it didn't work (see edit). Am I missing something?
Answer: Perhaps try using the transpose of the matrix to rotate your point cloud. See Rotation Matrix, which suggests that the matrix used to rotate the coordinate system and the matrix used to rotate an object are transposes of each other. The link also has useful information about defining a general transform matrix between two coordinate systems:
picture of general transform matrix
and the rotation matrix (which is the transpose):
picture of general rotation matrix
"where (x′,x) represents the angle between the x′ and x axes, (x′,y) is the angle between the x′ and y axes, etc."
How to get the rotation matrix to transform between two 3d cartesian coordinate systems? talks about using the identity transform as a reference between two coordinate systems when neither coordinate system is the coordinate system defined by the orthonormal vectors: (1,0,0); (0,1,0); (0,0,1)
Comment: Please, explain more and tell about the reasons of functionality of your suggestion.


How to add order status to commerce_line_item_table view in same way as in the commerce_user_orders view?

Question: I am trying to add user's order status to commerce_line_item_table view same as it is present in commerce_user_orders view. When user click on order no in commerce_user_orders view and it goes to commerce_line_item_table view here the order status is not present i want to add order status in this view. Any Help please
Answer: Well, you can add the Commerce Order: Order ID relationship to the view and then add the Commerce Order: Order status field and it'll provide the line item's order's status in the view.
Add the relationship:

Then, add the field:

Now, your view will have order status on the line items:


Factorizing expressions

Question: I am having trouble solving this problem $81f^2-  \dfrac{9}{e^2}$. How do you begin when solving this problem? Do you move $f^2$ by replacing the $9$ and vice versa and does the minus change to plus?
Answer: This expression is what is often termed a "difference of squares": one perfect square minus another—symbolically, $a^2-b^2$. It can be factored as $(a+b)(a-b)$.
In this case, we have $81f^2$, the square of $9f$, minus $9/e^2$, the square of $3/e$. The expression can therefore be factored, using the framework above, as $(9f-3/e)(9f+3/e)$.
Answer: You should notice that $81=9^2$ and $9=3^2$
You can then write the expression as $(9f)^2-(\dfrac 3e)^2$
It looks like $a^2-b^2$, isn't it? You should be able to finish from here.
EDIT: even if $81$ and $9$ were no squares, the method works, you just pu the square roots of the numbers...

Factorizing expressions


Help With Taxonomy

Question: I have a taxonomy menu of countries on the home page.  When the user clicks on a country they are taken to the specific country page where the country flag and country related content is displayed.  I achieved this using tags in the content, view with contextual arguments and the Panel page using the taxonomy term template.
On the country page is another taxonomy menu of sub-categories, (i.e.-movies, songs, tv).  When the user clicks on one of the items I want them to be take to another Panel page that will display the specific content that is ALSO filtered by the country that they selected in step one.
I am at a lose as to how to achieve this.  Any ideas?
Comment: in first case, it uses one contextual arguments, So in 2nd case, need to surely use 2 contextual arguments.
Answer: You'll need to somehow append the country tid as an additional filter to the menu links ( e.g theme function ) and use that as a contextual filter in the view for country + sub category.
Comment: i think your solution will work fine.

Help With Taxonomy


Using Markov's inequality

Question: If a point is chosen uniformly at random from the unit ball in $\mathbb{R}^{n}$ (that is, the set {($x_1$, $\dots$, $x_n$) : $x_1^{2}$+$\cdots$+$x_n^2$$\leq$$1$}), and $L_n$ is the distance of the point from the origin, I found that $E(L_n)$ is $\frac{n}{n+1}$.
However, I want to show that if a point if chosen uniformly at random from a high dimensional unit ball it is likely to be very close to the boundary. Hence, I want to use Markov's inequality to show that $L_n$$\rightarrow$$1$ in probability as $n\rightarrow\infty$.
I know that $P(X\geq t)\leq\frac{E(X)}{t}$ for any $t>0$, but I have difficulties proceeding after this.
Comment: I am porting my comment over from that thread -- Markov's inequality seems to point the wrong way so to speak. Since this problem has been reduced to 1 dimensional  and you were given a CDF-- use the CDF... for $\delta \in (0,1)$  you have $P(L\leq 1-\delta) = (1-\delta)^n \leq \exp(-\delta n)$
Comment: related: https://math.stackexchange.com/questions/3562951/continuous-random-variables-unit-ball-in-mathbb-rn
Answer: Let $D_n$ be the distance from the boundary so $D_n=1-L_n$ and $\mathbb E[D_n]=\frac{1}{n+1}$  and $\mathbb P(D_n\gt t )\lt \frac{1}{t(n+1)}$
Then, given any positive $\epsilon$ and $\delta$, for any $n> \frac{1}{\delta \epsilon}-1$ you have  $\mathbb P(D_n\gt \epsilon )\lt \frac{1}{\epsilon/(\delta \epsilon)}=\delta$
and so $D_n \to 0$ in probability as $n$ increases, and thus $L_n \to 1$ in probability
Comment: Thank you! Could you explain how you got $n> \frac{1}{\delta \epsilon}-1$?
Comment: @jacquesadit00  You want $n$ big enough to use an $\epsilon-\delta$ argument for the limit. How big is *enough*?  You want $\frac1{t(n+1)} \lt \delta$ when $t=\epsilon$.  This is $\frac1{\epsilon(n+1)} \lt \delta$ and $\frac1{n+1} \lt \delta\epsilon$, i.e. $n+1 \gt \frac1{\delta\epsilon}$ and $n \gt \frac1{\delta\epsilon}-1$
Answer: $P(L_n<t) \sim t^{n-1}$, hence the limit is 0 if $t<1$ and 1 if $t\ge1$. In this case convergence in distribution implies convergence in probability.
Comment: Hey, thank you for the answer. Could you explain how you got $t^{n-1}$?
Comment: I suspect that $P(L_n\le t) = t^{n}$ for $0 \lt t \lt 1$, but this does not affect the argument

Using Markov's inequality


how to count number of 0's and 1's of a number without applying any functions like decimal to binary conversion?

Question: I want to count the number of 0's and 1's in numbers from 0 to value.
(here in the code below value is 4,so count for 0,1,2,3).
If n and value are larger,it will give memory error due to large computation involved in decimal to binary computation.

def decimalToBin(n):

    l=[]
    while(n>0):
        dig=n%2
        l.append(dig)
        n=n//2
    l.reverse()
    return l

def main():
    n=2

    value=2**n

    for i in range(value):

        l=decimalToBin(i)
        m=l.count(0)
        n=l.count(1)
        print(m,n)

main()

Is there any way to get to know the count of 0's and 1's without actually applying decimal to binary conversion..?
Comment: Please check your formatting.  You should post code that we can copy/paste and run immediately without having to set variables.
Comment: To make sure - you want the count of each binary digit in numbers between 0 (inclusive) and `2^n` (exclusive)?
Comment: Yes,You're right@Amadan
Answer: This is a math problem, not a programming problem per se - though it is a good exercise for a programmer.
Let's say n=4 and try to see if we notice anything interesting. So we're dealing with these numbers:
   0
   1
  10
  11
 100
 101
 110
 111
1000
1001
1010
1011
1100
1101
1110
1111

The easiest observation is that the last bit toggles every row; the bit before it toggles every 2 rows; the next bit toggles every 4 rows, and the HSB toggles only once here (every 8 rows). The next thing you could note is that because of this, if we replaced the leading spaces with leading zeroes (i.e. if we made every row a 4-bit number), there would be exactly as many zeroes as ones. There would be 16 numbers (2^n), 4 bits each (n), so 64 bits in total (2^n * n), and 32 of them would be 1, and the remaining 32 would be 0. So the problem reduces to: how many leading spaces do we have?
Let's first consider the first row, as it is a bit anomalous - it is the only row that starts with a zero, because representing a number with no digits at all has proven to cause all sorts of problems. Let's pretend for now that zero is written as it logically would be - with no digits (and four leading spaces.) So, what do we have?
The last bit has just one leading space, the one in the "fixed" first row.
The second bit has two leading spaces.
The third bit has four leading spaces.
The MSB has eight leading spaces.
So we have the total of 1+2+4+8 leading spaces, which is 15 (2^4 - 1). We have to restore our first-row fix, and deduct one leading space (because we do want to write zero as 0, and not as nothing), so the correct number of leading spaces is 2^n - 2.
So we know that 2^n * n / 2 bits are 1.
And we know that 2^n * n / 2 - (2^n - 2) bits are 0. This can be simplified: 2^n * (n / 2 - 1) + 2
Lastly, note that Python writes exponentiation as **, not ^ (which is something different entirely). So...
num_of_ones = 2 ** n * n / 2
num_of_zeros = 2 ** n * (n / 2 - 1) + 2

Comment: Thanks a lot! In a similar way could you please tell me how to find for individual numbers and print it? Like for n=2, value=4, i want to count and print the number of 1's and 0's first for 0 then count and print for 1 and so on. for eg. for 0 - it is num_of_ones=0 and num_of_zeros=1 ,     for 1- num_of_ones=1 and num_of_zeros=0 ,      for 2-  num_of_ones=1 and num_of_zeros=1 and    for 3-  num_of_ones=2 and num_of_zeros=0 .
Comment: There are no patterns for individual numbers - you would need to convert the number to binary.


Programa em Python para salvar texto em bloco de notas

Question: Estou tentando fazer em python um programa que dá algumas opções de comida ao usario e depois as salva em um bloco de notas, mas está dando erro, o que há de errado?
erro:
Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\Casa\AppData\Local\Programs\Python\Python38\lib\tkinter__init__.py", line 1883, in call
    return self.func(*args)
  File "C:\Users\Casa\AppData\Local\Programs\Python\Python38\lib\tkinter__init__.py", line 3941, in call
    self.__var.set(self.__value)
AttributeError: 'NoneType' object has no attribute 'set'
from tkinter import *

janela = Tk()
janela.title("McDonald's")

def salvar_dados():
    f = open("pedidos.txt", "a")
    f.write(f"Nome: {nome.get()}\n")
    f.write(f"Pão: {pao.get()}\n")
    f.write(f"Carne: {carne.get()}\n")
    f.write(f"Salada: {salada.get()}\n")
    f.write(f"Tempero: {tempero.get()}\n")
    f.write(f"Condimentos: {condimentos.get()}\n")
    f.write(f"Acompanhamentos: {acompanhamentos.get()}\n")
    f.write(f"Bebidas: {bebidas.get()}\n")
    f.write(f"Observação: {observacao.get()}\n")
    #nome.set("Araras")
    nome.delete(0, END)
    observacao.delete("1.0", END)
    f.close()

def ler_pao(arquivo):
    leit1 = []
    f = open(arquivo, encoding="utf8")
    for linha in f: leit1.append(linha.rstrip())
    f.close()
    leit1.sort()
    return leit1

def ler_carne(arquivo):
    leit2 = []
    f = open(arquivo, encoding="utf8")
    for linha in f: leit2.append(linha.rstrip())
    f.close()
    leit2.sort()
    return leit2

def ler_salada(arquivo):
    leit3 = []
    f = open(arquivo, encoding="utf8")
    for linha in f: leit3.append(linha.rstrip())
    f.close()
    leit3.sort()
    return leit3

def ler_tempero(arquivo):
    leit4 = []
    f = open(arquivo, encoding="utf8")
    for linha in f: leit4.append(linha.rstrip())
    f.close()
    leit4.sort()
    return leit4

def ler_condimentos(arquivo):
    leit5 = []
    f = open(arquivo, encoding="utf8")
    for linha in f: leit5.append(linha.rstrip())
    f.close()
    leit5.sort()
    return leit5

def ler_acompanhamentos(arquivo):
    leit6 = []
    f = open(arquivo, encoding="utf8")
    for linha in f: leit6.append(linha.rstrip())
    f.close()
    leit6.sort()
    return leit6

def ler_bebidas(arquivo):
    leit7 = []
    f = open(arquivo, encoding="utf8")
    for linha in f: leit7.append(linha.rstrip())
    f.close()
    leit7.sort()
    return leit7

pedido_txt = "pedidos.txt"
paon = "Escolha o pão"
carnen = "Escolha a carne"
salan = "Escolha a salada"
tempn = "Escolha o tempero"
condin = "Escolha os condimentos"
acomn = "Escolha os acompanhamentos"
bebn = "Escolha as bebidas"

p1 = Label(janela, text="Pão: ").pack()
pao = StringVar()
pao.set(paon)

op1 = ler_pao("pao.txt")
OptionMenu(janela, p1, *op1).pack()

p2 = Label(janela, text="Carne: ").pack()
carne = StringVar()
carne.set(carnen)

op2 = ler_carne("carne.txt")
OptionMenu(janela, p2, *op2).pack()

p3 = Label(janela, text="Salada: ").pack()
salada = StringVar()
salada.set(salan)

op3 = ler_salada("salad.txt")
OptionMenu(janela, p3, *op3).pack()

p4 = Label(janela, text="Tempero: ").pack()
tempero = StringVar()
tempero.set(tempn)

op4 = ler_tempero("temp.txt")
OptionMenu(janela, p4, *op4).pack()

p5 = Label(janela, text="Condimentos: ").pack()
condimentos = StringVar()
condimentos.set(condin)

op5 = ler_condimentos("condi.txt")
OptionMenu(janela, p5, *op5).pack()

p6 = Label(janela, text="Acompanhamentos: ").pack()
acompanhamentos = StringVar()
acompanhamentos.set(acomn)

op6 = ler_acompanhamentos("acom.txt")
OptionMenu(janela, p6, *op6).pack()

p7 = Label(janela, text="Bebidas: ").pack()
bebidas = StringVar()
bebidas.set(bebn)

op7 = ler_bebidas("beb.txt")
OptionMenu(janela, p7, *op7).pack()

n = Label(janela, text="Nome: ").pack()
nome = Entry(janela)
nome.pack()

obs = Label(janela, text="Observação: ").pack()
observacao = Entry(janela)
observacao.pack()

sv = Button(janela, text="Salvar", command=salvar_dados)
sv.pack()

janela.mainloop()

Answer: Eu não tive esse erro mais sim: TypeError: init() missing 1 required positional argument: 'value' , já que nos OptionMenu você esqueceu de definir os variavel value
OptionMenu(janela, p2, *op2).pack()
quando deveria ser
OptionMenu(janela,carne,p2, *op2).pack()
from tkinter import *

janela = Tk()
janela.title("McDonald's")

def salvar_dados():
    f = open("pedidos.txt", "a")
    f.write(f"Nome: {nome.get()}\n")
    f.write(f"Pão: {pao.get()}\n")
    f.write(f"Carne: {carne.get()}\n")
    f.write(f"Salada: {salada.get()}\n")
    f.write(f"Tempero: {tempero.get()}\n")
    f.write(f"Condimentos: {condimentos.get()}\n")
    f.write(f"Acompanhamentos: {acompanhamentos.get()}\n")
    f.write(f"Bebidas: {bebidas.get()}\n")
    f.write(f"Observação: {observacao.get()}\n")
    #nome.set("Araras")
    nome.delete(0, END)
    observacao.delete(0, END)
    f.close()

def ler_pao(arquivo):
    leit1 = []
    f = open(arquivo, encoding="utf8")
    for linha in f: leit1.append(linha.rstrip())
    f.close()
    leit1.sort()
    return leit1

def ler_carne(arquivo):
    leit2 = []
    f = open(arquivo, encoding="utf8")
    for linha in f: leit2.append(linha.rstrip())
    f.close()
    leit2.sort()
    return leit2

def ler_salada(arquivo):
    leit3 = []
    f = open(arquivo, encoding="utf8")
    for linha in f: leit3.append(linha.rstrip())
    f.close()
    leit3.sort()
    return leit3

def ler_tempero(arquivo):
    leit4 = []
    f = open(arquivo, encoding="utf8")
    for linha in f: leit4.append(linha.rstrip())
    f.close()
    leit4.sort()
    return leit4

def ler_condimentos(arquivo):
    leit5 = []
    f = open(arquivo, encoding="utf8")
    for linha in f: leit5.append(linha.rstrip())
    f.close()
    leit5.sort()
    return leit5

def ler_acompanhamentos(arquivo):
    leit6 = []
    f = open(arquivo, encoding="utf8")
    for linha in f: leit6.append(linha.rstrip())
    f.close()
    leit6.sort()
    return leit6

def ler_bebidas(arquivo):
    leit7 = []
    f = open(arquivo, encoding="utf8")
    for linha in f: leit7.append(linha.rstrip())
    f.close()
    leit7.sort()
    return leit7

pedido_txt = "pedidos.txt"
paon = "Escolha o pão"
carnen = "Escolha a carne"
salan = "Escolha a salada"
tempn = "Escolha o tempero"
condin = "Escolha os condimentos"
acomn = "Escolha os acompanhamentos"
bebn = "Escolha as bebidas"

p1 = Label(janela, text="Pão: ").pack()
pao = StringVar()
pao.set(paon)

op1 = ler_pao("pao.txt")
OptionMenu(janela,pao,p1, *op1).pack()

p2 = Label(janela, text="Carne: ").pack()
carne = StringVar()
carne.set(carnen)

op2 = ler_carne("carne.txt")
OptionMenu(janela,carne,p2, *op2).pack()

p3 = Label(janela, text="Salada: ").pack()
salada = StringVar()
salada.set(salan)

op3 = ler_salada("salad.txt")
OptionMenu(janela, salada,p3, *op3).pack()

p4 = Label(janela, text="Tempero: ").pack()
tempero = StringVar()
tempero.set(tempn)

op4 = ler_tempero("temp.txt")
OptionMenu(janela, tempero,p4, *op4).pack()

p5 = Label(janela, text="Condimentos: ").pack()
condimentos = StringVar()
condimentos.set(condin)

op5 = ler_condimentos("condi.txt")
OptionMenu(janela, condimentos,p5, *op5).pack()

p6 = Label(janela, text="Acompanhamentos: ").pack()
acompanhamentos = StringVar()
acompanhamentos.set(acomn)

op6 = ler_acompanhamentos("acom.txt")
OptionMenu(janela, acompanhamentos,p6, *op6).pack()

p7 = Label(janela, text="Bebidas: ").pack()
bebidas = StringVar()
bebidas.set(bebn)

op7 = ler_bebidas("beb.txt")
OptionMenu(janela, bebidas,p7, *op7).pack()

n = Label(janela, text="Nome: ").pack()
nome = Entry(janela)
nome.pack()

obs = Label(janela, text="Observação: ").pack()
observacao = Entry(janela)
observacao.pack()

sv = Button(janela, text="Salvar", command=salvar_dados)
sv.pack()

janela.mainloop()

Para min não aparece o erro que você informou, mas tomara que isso ajude


Global click counter that counts clicks of all users

Question: I am quite green in the CSS, HTML and JS, but I wish to create click counter that counts all the clicks made by all the users.
ie. when the counter says "0" and if person A has opened the site and clicks the counter once the person B by clicking the counter once too gets result of "2" instead of "1".
I have watched many videos how to create the counter but it resets once the page is reloaded and that's not what I want.
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Counter App</title>

<link rel="stylesheet" href="counter.css">

Counter App

            <button class="btn decreased"> - </button>
             0
            <button class="btn increase"> + </button>

    // initial value of span ========

let value = 0

// getting value by reference ==========

const span = document.querySelector("span");
const decreased = document.querySelector(".decreased")
const increase = document.querySelector(".increase");

// --------- calling the even function -------------------

decreased.addEventListener("click" , () => {
    span.innerHTML=value--;

});

// --------------- event for increase button--------------------

increase.addEventListener("click" , () =>{
    span.innerHTML=value++;
})

*{
    margin 0%;
    padding: 0%;
    box-sizing: border-box;
    background-color: rgba(255, 166, 0, 0.644);

}
.container
{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: orange;
    border: 1px solid orange;
    border-radius: 20px;
    box-shadow: 5px 5px 4px 2px rgb(211, 161, 96);
    width: 300px;
    height: 200px;

}

h1{
    font-size: 30px;
    text-align: center;
    text-shadow: 2px 2px rgba(5, 5, 5, 5);
    color: white;

}

.button-counter{
    display: flex;
    justify-content: space-around;
    align-items: center;

}
button
{
    text-align: center;
    padding: 10px;
    margin: 10px;
    font-size: 30px;
    width: 60px;
    height: 60px;
    border-radius: 50%;
    background-color: rgba(255, 166, 0, 0.445);
    cursor: pointer;
    box-shadow: 5px 5px 5px rgba(255, 166, 0, 0.829);
    border: 1px solid rgb(231, 230, 230);
    font-weight: bolder;
    color: white;

}
button:hover{
    background-color: #fff;
    color: black;

}
span
{
    text-align: center;
    box-shadow: 5px 5px 4px 2px rgb(150, 143, 121);
    font-size: 32px;
    font-weight: bolder;

    border-radius: 10px;
    width: 50px;
    border: 1px solid rgb(90, 89, 89);
    color: rgb(36, 17, 33);

}

Comment: You need a server side code to keep track of all clicks from different users
Comment: Hi, unless you are counting users who access the page from one particular computer, in one particular browser, and under one particular user account on that computer, you will need to write server-side as well.
Comment: You must store the count vlaue somewhere (Database) and the refresh the value with javascript in front
Answer: If you want the next user to count from what the previous left, you need to store the data somewhere (for example on a database) and when the page loads first of all you read that value again and show it to the user.
The answer is no, you cannot do that with only CSS, HTML and JS.
Comment: psst.... nodejs ;)
Comment: Not trying to make it too complicated, what I meant is you cannot do that by just writing some code on a HTML file. Setting up a nodejs server might take a little more effort :P
Comment: yes. I know. still, nodejs is one fairly easy way to write server-side code using javascript.
Answer:
Best option to store public data on the frontend is local storage.
window.localStorage.setItem(name, data); // -> set item
window.localStorage.getItem(name); // -> get item

Disadvantages

can be changed using the DevTools
resets if cache is cleared

If you don't want that, you must use a database therefore you need a backend

EDIT: You need a database and a server to be able to shara data between multiple users and/or clients
Comment: I think, main disadvantage is that localstorage is not shared between users under different accounts, borwsers, computers
Comment: The question specifies that they want this stored counter variable to be shared between multiple users, so implementing local user-specific storage doesn't solve that aspect of the problem.
Comment: It can be if the users use the same client, but true. Database is needed
Comment: Nevermind my answer, I updated it


Wildcard subdomains for all domains

Question: So what I have at the moment (for each domain) is this
<VirtualHost *:80>

  ServerName exmaple.com
  ServerAlias *.example.com

  DirectoryIndex index.php index.html
  VirtualDocumentRoot /srv/www/example.com/public_html/%0

</VirtualHost>

But I'd like to save having to ever duplicate this for another domain by doing something like this
<VirtualHost *:80>

  ServerName *
  ServerAlias *

  DirectoryIndex index.php index.html
  VirtualDocumentRoot /srv/www/%2+/public_html/%0

</VirtualHost>

%2+ being all but the subdomain.
Is this even possible…
Answer: As long as you'd only have single-level subdomains, then that should work.  If you want to serve all your pages via mod_vhost_alias, just take the VirtualDocumentRoot line out of the <VirtualHost> directives, and eliminate all your <VirtualHost> directives.
You don't need to specify the wildcard ServerName.  It requires a FQDN anyway, so you can't use one anyway.  Similarly with ServerAlias, since VirtualDocumentRoot is taking care of finding the right places to serve pages from, it's not necessary to use since the Host: header will be processed dynamically.
Reading the docs on mod_vhost_alias and Dynamically configured mass virtual hosting should help clear up any remaining confusion.

Wildcard subdomains for all domains


How to use the path suffix in the Metatag page title?

Question: My articles currently have a Metatag page title [node:title]. Sometimes this results in duplicate page titles (articles can have the same title), which isn't desirable from a SEO point of view. Therefore, I would like to add a number after [node:title] when there already exists an article with the same title.
I use the Pathauto module, which adds a suffix to duplicate paths, so this suffix would be perfect. Can I use the path suffix in the Metatag page title? Or is there another possible solution?
Answer: The only token Pathauto provides is [node:url:args:join-path], the generated alias for the node. The suffix originates from, pathauto_alias_uniquify(&$alias, $source, $langcode), which Pathauto doesn't expose in any way; it's generated as needed to ensure the output alias is unique.
Theoretically, you could provide your a custom token that tries to find the value, but it would be error prone; pathauto isn't storing the suffix independently so there's no guarantee that a matched value is actually the suffix generated from Pathauto.
This is more of an editorial problem then a technical one. So a better solution would be to enforce unique titles at an authoring level.
For example, utilizing the Unique Content Title module to verify that each node title is unique upon submission.
Comment: Thanks for your suggestions. However, in my particular case it really is impossible to enforce unique titles. Even if I do so, a standard title is generated with the Automatic Nodetitles module when no title has been filled in by the user. Any other ideas to cope with this issue?
Comment: I don't know all the particulars of your requirements so it would just be speculative guesses. However, some function is probably evoked for auto nodetitles that you can evoke during a validation handler to compare for uniqueness.


Multiple python versions: How to set default python binary

Question: I have installed python 2.7.5 on CentOS 6.4 which python 2.6 already installed.
Python2.7 is under /usr/local/bin and library configuration is correct as well.
I set alias in .bash_profile as
alias python='/usr/local/bin/python2.7'
PATH=$PATH:/usr/local/bin

However, I need to do source .bash_profile each time I logged in and it's pretty annoying.
How can I change my default python version to python2.7.5?
Thanks
Answer: Logout from desktop environment, then login. And it will work.
(.bash_profile is not sourced when you login graphically.)
If that does not work put alias line to .bashrc.
Answer: Create a symbolic link python in /usr/bin and point it to /usr/local/bin/python2.7. Something like this should work:
ln -s /usr/local/bin/python2.7 /usr/bin/python

Make sure you have permissions to do that. Once done, hit python command and it should get you to python 2.7
Hope this helps.
Comment: Because some tools are dependent on default version of python, overwriting /usr/bin/python will break those tools.
Comment: I believe python 2.7 is completely backward compatible with python2.6 and below (unlike 3.x).
Comment: If dependent module is pure python, it will be run in Python 2.7. But if it is extension module, it will not.
Comment: Enen though the module is pure python, there could be problem. Imagine that there was some script name /usr/bin/abc which import module xyz. Module xyz is not installed for Python2.7, only for Python2.6 unless you manually install such modules. (/usr/lib/python2.6/site-packages/xyz/....)
Comment: See [this question](http://stackoverflow.com/questions/10624511/upgrade-python-without-breaking-yum).
Comment: I agree with this. :)


JSF mudar informações no XHTML

Question: Boa noite.
Tenho uma aplicação em java/jsf estou com uma dificuldade em mostrar informações no XHTML,
Bem eu tenho um SelectOneMenu para salvar uma informação no banco:

    <f:selectItem itemLabel="Selecione" itemValue="" />
    <f:selectItems value="#{permissaoView.permissoes}" />
    <f:validateLength minimum="1" />

Ele puxa as informações de uma classe chamada PermissaoView:
 @PostConstruct
    public void init() {
        permissoes = new HashMap<String, String>();
        permissoes.put("Supervisor", "1");
        permissoes.put("Atendente", "2");
        permissoes.put("Pronta Resposta", "3");
    }

Por causa de algumas regras de negocio ele salva no banco os valores 1, 2 e 3
Ok, ele salva no banco, quando eu puxo as informações em um dataTable é lógico que ele vai puxar as informações 1, 2 e 3. aqui esta a linha do código que puxa a informação no datatable é essa:

        <h:outputText value="#{listausuario.permissaoAcesso}" />

como eu disse, ele mostra as informações que eu salvei, que no caso são 1, 2 e 3, agora minha dificuldade é no xhtml mudar esses dados para para os nomes de cada valor exemplo valor 1 no datatable mostrar Supervisor, vi em alguns lugares na net que eu posso usar Enum, mas não sei bem como ele funciona. Alguem pode me dar uma luz? Obrigado.
Answer: O melhor seria usar enum.
Do jeito que está, a solução é a seguinte:
1 - Crie este método na sua classe:
public String permissaoAcessoFormatada(){
   switch (permissaoAcesso) {
     case "1":
     return "Supervisor";
     case "2":
     return "Admin";
     case "3":
     return "Mestre";
     default:
     return null;
   }
}

2 - Use o método no seu dataTable:

        <h:outputText value="#{listausuario.permissaoAcessoFormatada()}" />

Comment: Perfeito man, deu certinho, obrigado.

JSF mudar informações no XHTML