Fetch userdata on each request

Question: My problem is quite simple - I think. I'm doing an ASP.NET MVC project. It's a project that requires the user to be logged in at all time. I probably need the current user's information in the MasterPage, like so; "Howdy, Mark - you're logged in!".
But what if I need the same information in the view? Or some validation in my servicelayer?
So how to make sure this information is available when I need it, and where I need it?
Answer: How much user information do you need? You can always access the Thread.Current.Principal and get the user's name - and possibly use that to look up more info on the user in a database.
Or if you really really really need some piece of information at all times, you could implement your own custom principal deriving from IPrincipal (this is really not a big deal!), and add those bits of information there, and when the user logs in, create an instance of the MyCustomPrincipal and attach that to the current thread. Then it'll be available anywhere, everywhere, anytime.
Marc
Answer: I've had exactly the same issue, and have yet to find a satisfactory answer. All the options we've explored have had various issues. In the specific example you mention, you could obviously store that data in the session, as that would work for that example. There may be other scenarios, that we've had, where that may not work, but simple user info like that would be fine in the session.
We've just setup a BaseController that handles making sure that info is always set and correct for each view. Depending on how you're handling authentication, etc, you will have some user data available in HttpContext.User.Identity.Name at all times. Which can also be referenced.
Answer: Build a hierarchy of your models and put the shared information in the base model. This way it will be available to any view or partial view.
Of course it has to be retrieved on each request since web applications are not persistent.
Answer: You should store this in Session and retrieve it into your controllers via a custom ModelBinder.
Comment: The only issue where we've had problems using the session is for data that may vary depending on the area of the site you're in. For example, we have a series of Leagues in one of our apps where sometimes the user may be a manager, sometimes not. We have to store whether a user is a manage in the session. This works great until you have multiple tabs open, and then it all starts getting very messy. So it works for login info, but falls down when you start using it for other data potentially.
Comment: Can you explain that part of your problem in more detail? It sounds as if you want to look at federating your login model using roles to a greater extent.
Comment: It's not quite that simple, we have a single user who may have multiple roles within different elements of the site. marc_s's suggestion below might actually address that issue for us. We're having a play with it some more to see if it provides a good solution.
Answer: Not sure if I get what you want to ask, but if you are looking for things like authentication and role-based authorization, actually ASP.net is providing a great framework to work on/start with.
This article (with also 2nd part) is something I recently discovered and read about which is really good start with the provider-pattern which help to understand the underlying authentication framework of ASP.net. Be sure to read about the membershipProvider class and the RoleProvider class in msdn also, they together make a great framework on most basic role-base authentication to work with (if you are comfortable with the function they provided, you even don't need to code data-access part, all are provided in the default implementation!)
PS: Check out Context.Users property too! It stores the current authenticated user information.
Answer: HttpContext.Current.Users.Identity returns the current user's information. Though I am not sure whether it gets passed implicitly when you make a webservice call.

Fetch userdata on each request


Prove that $x_{n+1}=\frac{x_n}{2}+\frac{1}{x_n}\geq\sqrt{2}$

Question:
Let $(x_n)_{n\in\mathbb N}$ be a recursively defined sequence with $x_1=9$ and
  $$x_{n+1}=\frac{x_n}{2}+\frac{1}{x_n}\text{ for }n\geq 1.$$
  Show that $x_n\geq\sqrt{2}$ for all $n$.

Because $x_n\geq 0$ one can easily prove inductively that $$x_n^2\geq 2\Leftrightarrow x_n^2-2\geq 0\Leftrightarrow\left(\frac{x_{n-1}}{2}-\frac{1}{x_{n-1}}\right)^2\geq 0,$$ hence $x_n\geq\sqrt{2}$. However I have seen another approch which I was very curious about because I don't have the feeling that this can be done without proper justification other than the induction hypothesis:
$$x_{n+1}=\frac{x_n}{2}+\frac{1}{x_n}\overset{(*)}{\geq}\frac{\sqrt{2}}{2}+\frac{1}{\sqrt{2}}=\sqrt{2}$$
For $(*)$ it is assumed that $x_n\geq\sqrt{2}$ holds for an $n\in\mathbb N$. Are there any objections about this consideration?
Comment: A straightforward approach to showing that $x_n\ge \sqrt{2}$ is to write

$$x_{n}-\sqrt{2}=\left(\frac{x_{n-1}}{2}+\frac1{x_{n-1}}\right)-\sqrt{2}=\frac{(x_{n-1}-\sqrt{2})^2}{2x_{n-1}}\ge0$$
Comment: Hint: AM-GM inequality is fast. Your second approach is flawed, as the reciprocal term does not follow in the inequality *
Comment: The inequality $\frac{1}{x_n} \geq \frac{1}{\sqrt{2}}$ is false because it would imply that $x_n \leq \sqrt{2}$ (this is true only if $x_n=\sqrt{2}$ but else.... )
Comment: @Dr.MV By far the simplest.
Comment: @Dr.MV Yeah pretty similiar to my explained approach in the first part of my post. I was just wondering about the other approach and its correctness there.
Comment: Yes, similar.  This form is a bit more transparent and the development thereof is direct.
Answer: If you know derivatives you can make it work as follows.
Consider the function :
$$f(x)=\frac{x^2+2}{2x}$$
Now calculate the derivative :
$$f'(x)=\frac{2x^2-4}{4x^2}\geq 0 $$ if $x\geq \sqrt{2} $ so the function is increasing for $x\geq \sqrt{2}$
Now from the induction hypothesis $x_n\geq \sqrt{2} $ so from the monotony :
$$x_{n+1}=f(x_n)\geq(\sqrt{2})=\frac{4}{2\sqrt{2}}=\sqrt{2}$$ as wanted .
Answer: Although the following goes a bit beyond addressing the OP's question, I thought that it would be instructive.  So, let's have a look at the sequence generated by the recurrence relationship  $x_n=\frac12 x_{n-1}+\frac{1}{x_{n-1}}$.
This is actually an interesting recursively generated sequence.  If we examine the first difference $x_{n}-x_{n-1}$ we find that
$$x_{n}-x_{n-1}=\frac{2-x_{n-1}^2}{2x_{n-1}} \tag 1$$
We deduce immediately from $(1)$ that if $x_n > \sqrt{2}$, then $x_n$ is decreasing while if $x_n<\sqrt{2}$, then $x_n$ is increasing.
Now, a straightforward approach to showing that $x_n\ge \sqrt{2}$ is to write
$$x_{n}-\sqrt{2}=\left(\frac{x_{n-1}}{2}+\frac1{x_{n-1}}\right)-\sqrt{2}=\frac{(x_{n-1}-\sqrt{2})^2}{2x_{n-1}}\ge0 \tag 2$$
regardless of the value of $x_{n-1}$.
Therefore, the only value of the sequence that can ever be less than $\sqrt{2}$ is its initial "seed" value.  From $(1)$, we see that if the seed value is less than $\sqrt{2}$, the subsequent value increases.  And $(2)$ shows that it increases above $\sqrt{2}$.  Then, the remaining sequence decreases monotonically to the limit value of $\sqrt{2}$.
Answer: Yes, you can make the assumption $x_n\ge \sqrt{2}$ to prove $x_{n+1}\ge \sqrt{2}$ as per strong form of mathematical induction.
But your reasoning is wrong as $x_n\ge \sqrt{2} \Rightarrow \frac{1}{x_n} \le \frac{1}{\sqrt{2}}$.
Better is to use AM-GM inequality as Macavity has mentioned since the quantities are all positive.
$$\frac{\frac{x_n}{2}+\frac{1}{x_n}}{2}\ge \sqrt{\frac{x_n}{2}\cdot\frac{1}{x_n}}$$
$$x_{n+1}\ge \sqrt{2}$$
Answer: Hint: study the function $f(x)=x/2 +1/x$ it increases if $x>\sqrt2$


Who will progress to the semi-final/final in case of equal points?

Question: I run the stats for a cricket comp, and at the end of the season the point table looks like this:
<code>TEAM    P   W   D   L   FIP BP  PTS
Ninjas  6   3   1   2   10  6   30
Charger 6   3   0   3   8   6   26
Hawks   6   3   2   1   4   6   26
Wolves  6   1   1   4   2   2   10
</code>
And because I store everything in a database running a query gives it to me automatically.
For the finals, top of the ladder (Ninjas) goes through to the final, and will play the winner of 2 v 3. The Chargers and Hawks are level on points. Head to head between Chargers and Hawks is 1 all. Should the Chargers be in second or the Hawks to get the home semi?
Comment: As @hims056 has indicated, there is no universal rule to decide which team qualifies. Each tournament has its own rules. Therefore this question cannot be answered without knowing what the rules are of this tournament. If this is a tournament that you have organised, then you can decide what rules to apply (e.g. most FIP points; most FP points; toss of a coin; etc.). Ideally, though, this should have been done before the tournament starts, to avoid complaints.
Comment: There are no universal rules on this. The Universe doesn't ordain how tournaments should be run, the organisers of each one need to decide on the rules for their tournament. As the organisor of this one, you'll have to make that decision. There's no objective moral philosophy out there that can give you this answer. If you haven't made the rules in advance and now find yourself in a sticky situation where your ruling will decide who goes through then simply acknowledge that and make a decision. There is no Oracle that will allow you to out-source that decision at this point.
Comment: @user1672694 First, welcome to Sports SE! Happy to have you. Second, let's keep it cordial. Our users are here to help you. If there is something they don't understand, they are requesting clarification. Thus, this detail they are requesting will potentially help them answer your question.
Comment: What is `FIP` and `BP`?
Comment: @hims056 first innings points and bonus points.
Comment: @Spinner, let me rephrase the question then. Generally speaking, *in most cases* aka *example with the most precedents* who would be second and who would be third?
Comment: @edmastermind29 'If there is something they don't understand, they are requesting clarification' there hasn't been any.
Comment: @user1672694 Been any what? Let us help you.
Comment: @edmastermind29 any clarification. All that has been asked is what tournament it is so that they can look it up on cricinfo and if it existed on cricinfo I would have done so by now. But it doesn't.
Comment: @Bogdanovist I didn't organize it, if you take the time to read all the comment you would know that. The universe doesn't ordain what help is either, as is apparent from everything you see here. I've told you what I want, stop trying to backup the lack of answer
Answer: The rules regarding berth in the semi-finals/finals in case of equal points are defined for particular tournament. E.g. in the West Indies Tri-Nation Series, 2013 (Between West Indies, India and Sri Lanka) the rules regarding berth in the finals in case of equal points were as follow:

In the event of teams finishing on equal points, the right to play in
  the final match or series will be determined as follows:

The team with the most number of wins
If still equal, the team with the most number of wins over the other team(s) who are equal on points and have the same number of wins
If still equal, the team with the highest number of bonus points
If still equal, the team with the highest net run rate

So the above rules were for that particular tournament. Take a look at another example: In the ICC Champions Trophy, 2013 the rules for berth in semi-finals were as follow:

In the event of teams finishing on equal points in its Group, the
  right to play in the semi-finals will be decided in the following
  order of priority:

The team with the more wins in the Group stage will be placed in the higher position.
If there are teams with equal points and equal wins in the Group stage then in such case the team with the higher net run rate in the
  Group stage will be placed in the higher position (refer below for the
  calculation of net run rate).
If still equal, the team which was the winner of the head to head match played between them will be placed in the higher position.
In the highly unlikely event that teams cannot be separated by the above this will be done by drawing lots.
If all of the matches within a Group are a no result, the top two seeded teams will progress to the semi-finals.

Since there are different rules for different tournaments we can't say which team will progress to the final in the above case. Also you can see such rules for the current tournament from www.espncricinfo.com. Just go to the series page -> open Point Table. Such rules are available in the Point Table page.
E.g. Champions League Twenty20, 2013/14 -> the Point Table page.
Comment: No, examples is not specific, it's not answerable (in any coherent way). You're asking a question with no *right* answer. You want a question that might have several dozen correct answers, with no qualifications on how to test said potentially correct answers. **If you want help devising a tiebreaker scheme, then give some requirements for what kind of outcome you desire.** Asking what every league ever does is silly.
Comment: @user1672694 From what I gather, you ask who should be ranked higher (Chargers or Hawks) given equal points. The answer has been, "there is no universal rule." hims056 has provided examples of how other tournaments handle it *because* there is no universal rule. So, *what the rules **should** be* is based on what tournament and/of set of rules you are following, which seems to be generic and unspecified. Hence, the questions.
Comment: @user1672694 Hence, your question has been closed for being "[primarily opinion-based](http://sports.stackexchange.com/help/closed-questions)."  Our users have provided facts and references to help you out, but you are requesting opinions on how to handle your specific situation. Please review the link above and our help center for more information.
Comment: @user1672694 - I didn't say *I don't know*. I said the rules for different tournaments are different. So you need to specify the tournament you are talking about. Then we can answer exact who will progress..
Comment: @user1672694 hims056 is requesting more detail about the specifics of the tournament, the series of rules, etc. you present. This will help him answer the question. Being defensive to these requests will not help you in obtaining an adequate answer.
Comment: @user1672694 And *in most cases*, this has been applied differently to different situations. ***What is usually used** to handle equal points to determine ranking?* is your question...which may or may not have a concrete answer. Again, no need to pontificate negativity toward others...hims056 provided sources and quoted text in accordance to the [Creative Commons](http://creativecommons.org/licenses/by-sa/3.0/us/) license to help you out.
Comment: @edmastermind29 the issue with me deciding is bias. I know what I would do personally, but I may be seen as biased and I wish to avoid it. Hence why I am asking a community in a neutral position
Comment: You should probably avoid a wall of text just to say 'I don't know'. You would be better off using rules for first class cricket, seeing as that is the format.
Comment: @user1672694 - Also why do we use the rules of first class cricket in any tournament when that tournament has it's own rules?
Comment: I'm saying if you would have been better providing examples such as sheffield shield or county championship etc as they are more relevant.
Comment: @user1672694 - Why are those tournaments more relevant? Giving specific series' example has nothing to do with my point.
Comment: The why did you provide examples in the first place?
Comment: @user1672694 - Just avoid the examples. You will get your answer even after avoiding the examples.
Comment: @edmastermind29 the thing everyone has missed is that I'm asking *what the rules **should** be*
Comment: @edmastermind29 like I said before, *in most cases*, in other words, *in this situation what is usually used*. Yes he gave examples, but they were irrelevant, as I pointed out.
Comment: @edmastermind29 and what did he say? The rules are what the rules are for my comp. If I knew I wouldn't be asking.
Comment: @user1672694 "I run the stats for a cricket comp" -- Who or what is the "cricket comp?" Is this what you are unclear on?
Comment: @edmastermind29 competitions aren't people
Comment: @user1672694 but there are people who organize the competition, right? Let me rephrase, **what** is the "cricket comp?" Is this what you are unclear on?
Comment: @edmastermind29 *was* a person but there isn't anything in place for such a situation. Hence why I came here. I expected to get an answer such as 'in most cases this is how it is', not someone saying 'I can't tell you because everything is different'
Comment: @user1672694 Then my advice for you is *you decide.* You request to have our users determine which set of rules have been used most often from tournament to tournament to help you with your specific situation. hims056 and spinner has stated that there are "different rules for different tournaments." hims056 has provided examples of how this case is treated for different tournaments. If *most cases* cannot be readily determined, providing differences and examples are there to help you out...not to sidestep your question.
Comment: @user1672694 I see...bias is a different perspective you present, and is an uncomfortable situation to be in. Why not incorporate a coin toss? 50/50 chance. Thus, are you asking for **opinions** on how to handle this situation?
Comment: @edmastermind29 I'm looking for someone to say 'I say it should be done like this because x y and z did it like this'
Comment: @edmastermind29 no I am requesting relevant examples, not example provided to say 'look they're different so I can't answer the question'
Comment: @user1672694 That's not the kind of question that we deal with on SE sites. What you're asking for is not answerable. This is a valiant effort at an answer, but really we want specific, answerable questions. This question isn't one.
Comment: @waxeagle I'm asking for relevant examples. Not examples to backup the lack of substantial answer. This is answerable, obviously no-one wants to.


In IntelliJ IDEA, how do I disable the auto-format on simple methods

Question: After making simple methods such as:
<code>    public int getWidth() {
        return game.getWidth();
    }

    public int getHeight() {
        return game.getHeight();
    }

    public Game getGame() {
        return game;
    }
</code>
It will be reformatted as:
<code> public int getWidth() { return game.getWidth();}

    public int getHeight() { return game.getHeight();}

    public Game getGame() { return game;}
</code>
In the settings under Editor >> Code Style >> Java >> Keep when reformatting,
I have the box for "simple methods in one line" unchecked and it still happens. How can I fix this?
Answer: Just saying, it's not that bad since you can click on the method and it expands it.
But you can click File | Settings | Editor | General | Code Folding and click Collapse by Default. Then uncheck One-Line Methods under the Java section.


Erro de Conexão com o Banco de Dados em ANDROID

Question: Criei um banco de dados no localhost, e queria puxar este banco de dados para o meu Android, criei duas classes, a CONEXAODAO, e a ConexaoMYSQL:
public class conexaoDAO {

    public String tabelaDepartamento () {
        String departamentoNome = "";

        conexaoMysqlActivity conexao = new conexaoMysqlActivity();
        conexaoActivity objConexao = new conexaoActivity();

        objConexao.db_connect_string = "localhost";
        objConexao.db_name = "souprogresso";
        objConexao.db_userid = "root";
        objConexao.db_password = "";
        Connection conn = conexao.dbConnect(objConexao);
        if (conn != null) {
            try {
                   Statement statement = conn.createStatement();
                   String queryString = "SELECT nomeDepartamento, idprefeituraDepartamento FROM departamento WHERE idprefeituraDepartamento = '1'";
                   ResultSet rs;
                   rs = statement.executeQuery(queryString);
                   if (rs.next()) {
                       departamentoNome = rs.getString("nomeDepartamento");
                       System.out.println(departamentoNome);
                   }
            } catch (SQLException e) {
                departamentoNome = e.getMessage();
            }
        }
        return departamentoNome;
    }

}

public class conexaoMysqlActivity {
     @SuppressLint("NewApi")
     public Connection dbConnect(conexaoActivity objConexao) {
          StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
          StrictMode.setThreadPolicy(policy);
          Connection conn = null;
          String connectionUrl = null;

          try {
              Class.forName("com.mysql.jdbc.Driver");
              connectionUrl = "jdbc:mysql://" +
                      objConexao.db_connect_string + ";" +
                      "databaseName=" + objConexao.db_name + ";user="
                      +objConexao.db_userid +
                      ";password=" +  objConexao.db_password + ";";
              conn = DriverManager.getConnection(connectionUrl);

          } catch (SQLException se) {
              se.printStackTrace();
              System.out.println("Não foi possível se conectar com a base de dados");
          } catch (ClassNotFoundException e) {
              e.printStackTrace();
              System.out.println("Erro de Classe SQL");
          } catch (Exception se) {
              se.printStackTrace();
              System.out.println("Erro de Expressão");
          }
          return conn;
     }
}

Quando tento rodar acontece o seguinte erro:
08-14 17:48:30.149: E/AndroidRuntime(674): FATAL EXCEPTION: main
08-14 17:48:30.149: E/AndroidRuntime(674): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{br.com.example.secretario/br.com.example.secretario.conexaoMysqlActivity}: java.lang.ClassCastException: br.com.example.secretario.conexaoMysqlActivity cannot be cast to android.app.Activity
08-14 17:48:30.149: E/AndroidRuntime(674):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1880)
08-14 17:48:30.149: E/AndroidRuntime(674):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
08-14 17:48:30.149: E/AndroidRuntime(674):  at android.app.ActivityThread.access$600(ActivityThread.java:123)
08-14 17:48:30.149: E/AndroidRuntime(674):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
08-14 17:48:30.149: E/AndroidRuntime(674):  at android.os.Handler.dispatchMessage(Handler.java:99)
08-14 17:48:30.149: E/AndroidRuntime(674):  at android.os.Looper.loop(Looper.java:137)
08-14 17:48:30.149: E/AndroidRuntime(674):  at android.app.ActivityThread.main(ActivityThread.java:4424)
08-14 17:48:30.149: E/AndroidRuntime(674):  at java.lang.reflect.Method.invokeNative(Native Method)
08-14 17:48:30.149: E/AndroidRuntime(674):  at java.lang.reflect.Method.invoke(Method.java:511)
08-14 17:48:30.149: E/AndroidRuntime(674):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
08-14 17:48:30.149: E/AndroidRuntime(674):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
08-14 17:48:30.149: E/AndroidRuntime(674):  at dalvik.system.NativeStart.main(Native Method)
08-14 17:48:30.149: E/AndroidRuntime(674): Caused by: java.lang.ClassCastException: br.com.example.secretario.conexaoMysqlActivity cannot be cast to android.app.Activity
08-14 17:48:30.149: E/AndroidRuntime(674):  at android.app.Instrumentation.newActivity(Instrumentation.java:1023)
08-14 17:48:30.149: E/AndroidRuntime(674):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1871)

Answer: Faltou estender Activity:
public class conexaoMysqlActivity extends Activity {


Python Concatenate N dictionaries with highest values for each key

Question: I would like to create a new dictionary from dictionaries.

all keys in all dictionaries must be present in resulting dictionary
all keys must be present only once
value for key is highest value from all values in dictionaries

ex.
d1 = {'a':1, 'b':3}
d2 = {'a':5, 'd':5}
d3 = {'c':2, 'f':1}

d = {'a':5, 'b':3, 'c':2, 'd':5, 'f':1}

Also, I would like keys (that are strings) to be sorted, like in my example. I try with update. However, it is overwriting existing value with the newest value, not the highest value.
Answer: >>> from collections import Counter
>>> d1 = {'a':1, 'b':3}
>>> d2 = {'a':5, 'd':5}
>>> d3 = {'c':2, 'f':1}
>>> Counter(d1) | Counter(d2) | Counter(d3)
Counter({'a': 5, 'd': 5, 'b': 3, 'c': 2, 'f': 1})

This uses the union of multisets through collections.Counter
If you need the result sorted:
>>> from collections import Counter, OrderedDict
>>> OrderedDict(sorted((Counter(d1) | Counter(d2) | Counter(d3)).items()))
OrderedDict([('a', 5), ('b', 3), ('c', 2), ('d', 5), ('f', 1)])

This can be generalized for N dictionaries by using reduce
>>> from functools import reduce
>>> from operator import or_
>>> reduce(or_, map(Counter, (d1, d2, d3)))
Counter({'a': 5, 'd': 5, 'b': 3, 'c': 2, 'f': 1})

Comment: That's a pretty dense one-liner.
Comment: @Blender Now I changed to use `Counter` instead and deleted other answer


How to check ftp connection logs on CentOS?

Question: My website is running on Linux CentOS digitalocean. Is there any way to check ftp connection logs or currently opened ftp connections? I would like to make sure nobody else uses the ftp username.
Answer: Yes, you can.
The location of the logs depend on the service you're using but usually the location is /var/log .
Let's say you use proftpd service... you'll find its logs in /var/log/proftpd/proftpd.log and for other FTPd services in their respective paths in /var/log.
It's possible that your configuration saves logs in a different path than the default one.
In order to find which FTPd service your server runs, run:
netstat -plunt | grep ftp

This will show you which process holds the FTP port and then you'll know the service name.
Next thing is to locate that service's logs.


Need to change background image onmouseover in a jquery site

Question: hecked up trying a onmouseover background image change event for a link in a jquery site, if anyone knows it, please answer this with a demo!
Comment: Why you need jQuery, this can be done using pure css? Or isn't it the link itself whose bg you like to change?
Answer: Assumption: you have a transparent background image like the one in this example.
Working demo at: http://jsfiddle.net/marcosfromero/Bytmn/
$('#logo').hover(function() {
    $(this).addClass('highlighted');
}, function() {
    $(this).removeClass('highlighted');
});

You'll need an image with logo id and a CSS rule for the highlighted class.
jQuery hover expects two functions to be called:

One mouse is over (mouseenter event)
One mouse is out (mouseleave event)
Answer: a
{
background:#ffffff url('path-of-your-mouseout-image.jpg') no-repeat top left;
}

a:hover
{
background:#ffffff url('path-of-your-mouseover-image.jpg') no-repeat top left;
}

CSS CAN DO IT BUDDY.
Comment: Please dont forget to mark an answer as correct by clicking the tick mark on the left @johnsaxon


arquivo de lote para criar banco de dados mysql

Question: Estou tentando criar um arquivo de lote .bat para criar o banco de dados e depois recuperar inaformações via arquivo sql, segue o procedimento do arquivo .bat:
@echo off
cls
@echo.
@echo Instalando DB
cd C:\Program Files\MySQL\MySQL Server 5.6\bin\
mysql.exe -u root -proot CREATE DATABASE BDNAME
mysql.exe BDNAME < C:\Users\BD.sql
pause

O problema é que o código apenas faz o login no MYSQL no shell e não executa os outros procedimentos, como posso arrumar isso ou fazer de outra forma?
Answer: A sintaxe para usar um comando SQL na mesma linha é essa:
mysql  --execute="statement"
mysql  -e "statement"

No seu caso:
mysql.exe -u root -proot -e "CREATE DATABASE BDNAME"

(ou você pode simplesmente editar o seu BD.sql e por o create database dentro dele, eliminando a 1a chamada ao mysql.exe)
Mais detalhes na documentação oficial en.
Nota: não se esqueça de colocar os parâmetros de login (-u USER -pSENHA) no segundo comando, pois é uma sessão totalmente independente (a não ser que você esteja logando no .sql usado, claro)
Comment: obrigado! Vou fazer isso para ficar tudo em um .SQL.
Answer: A resposta do @Bacco já lida com os teus problemas imediatos, vou deixar uma forma ágil de lidar com a questão:
MySQL em modo batch
MySQL pode ser executado em modo batch, o que essencialmente nos permite passar como parâmetro um ficheiro que contém todos os comandos a executar:
mysql -h host -u user -p < ficheiro-batch

Assim, não é necessário estar constantemente a chamar:
 mysql -h host -u user -p -e "comando"

Em suma, dentro do ficheiro-batch podes ter TODOS os comandos a executar e com uma só linha resolver a questão.
Nota:
Nunca guardar a password neste tipo de ficheiros, se não a indicares, ao executares o que sugiro em cima, a mesma vai-te ser solicitada! Assim não corres riscos de segurança.
Comment: obrigado respostas nunca são demais.


Configure production environment in a create-react-app(SyntaxError: Unexpected token < in JSON at position 0)

Question: I want to configure production environment in my app (using create-react-app).
Maybe it's a silly question to ask because I'm searching and there are lots of articles about this but none of this helped me. Also, I used codes in create-react-app here(production) and here(development) but still not working.
For server side, I'm using node and all API are working well with development mode in react. but when I'm using production mode It's not working.
It's just returning

SyntaxError: Unexpected token < in JSON at position 0

in the browser console.
I can't access my routes in the server in production mode.
How can I solve it? Help appreciated.
This is my app tree, front-end folder includes my react code and running on a different port (server: 3000, react: production:3001, development:5000).
I have added this lines of code to app.js :
app.use(express.static(path.join(__dirname, 'front-end/build')));
 app.get('*', function (req, res) {
 res.sendFile(path.join(__dirname, 'front-end/build', 'index.html'));
 });

and this in www.js:
if (process.env.NODE_ENV === 'production') {
app.use(express.static('front-end/build'));
 }

Comment: Is there any answer?
Answer: I found my answer and my app is working in production mode now, and I have deployed it.
I just added this lines into my app.js in the root directory in server-side code(node application):
let root = path.join(__dirname, '..', 'myapp/fron-end/build');
  app.use(express.static(root));
  app.use(function(req, res, next) {
  if (req.method === 'GET' && req.accepts('html') && !req.is('json') &&
     !req.path.includes('.')) {
         res.sendFile('index.html', { root });
    } else next();
  });

Here myapp is the name of my project folder(server-side) and fron-end is the name of my front-end folder that includes builds folder that has created for production. (I put my front-end folder inside server-side folder)
This link helps me.
Uncaught SyntaxError: Unexpected token < #1812
Hope this helps others.


Critical points of $g(x, y) = x^3+3xy^2-12x-6y$

Question:
Find the critical points of $g(x, y) = x^3+3xy^2-12x-6y$.

$\nabla g(x, y) = (3x^2+3y^2-12, 6xy-6)$ so $\nabla g(x, y) = 0 \implies  (3x^2+3y^2-12, 6xy-6) = (0,0)$
So $x^2+y^2 -4 = 0$ and $xy = 1$; combining and writing it in two different ways we get:
$\begin{aligned} &\begin{cases} x^2+2xy+y^2 = 6xy \implies (x+y)^2 = 6 \implies x+y = \pm  \sqrt{2}\sqrt{3} \\ x^2-2xy+y^2 = 2xy \implies (x-y)^2 = 2 \implies x-y = \pm \sqrt{2} \end{cases}  \\& \implies (x,y) = (\pm \dfrac{1}{\sqrt{2}}(1+\sqrt{3}), \pm \frac{1}{\sqrt{2}}(\sqrt{3}-1))   ~ \text{are the critical points}.\end{aligned}$
This disagrees with the answer that wolfram alpha is giving me. What did I do wrong?
Comment: How did you go from $$x^2 + 2xy + y^2 = 6xy$$ to $$(x + y)^2 = 6$$ ?? The RHS should still be $6xy$.
Comment: @Mattos $xy=1$...
Comment: Wait are wolfram alpha's and mine the same?
Answer: Your method can't find two other critical points. You successfully found that $x+y=\pm \sqrt{6}$ and $x-y=\pm \sqrt{2}$, but plus and minus signs don't need to coincide. Then four possibilities occur:

$x=\dfrac{\sqrt{6}+\sqrt{2}}{2}$
$x=\dfrac{\sqrt{6}-\sqrt{2}}{2}$
$x=\dfrac{-\sqrt{6}+\sqrt{2}}{2}$
$x=\dfrac{-\sqrt{6}-\sqrt{2}}{2}$

Here 2 and 3 are missing in your attempt.


No numFmt in Styles.xml

Question: I am analyzing an OpenXML Excel file. I check the styles.xml, I find many entries like this:
<xf numFmtId="0" [..]>

However, there are no <numFmt> element in the styles.xml file at all. In such a case, how can I determine the number format for that style?
Answer: If the user applies a custom number format then the styles.xml file will contain numFmt elements like this with a numFmtId and formatCode:
<numFmts count="1">
  <numFmt
    numFmtId="165"
    formatCode="0.000"/>
</numFmts>

The numFmtId is then used in the <xf> element to reference the number format.
However, if the user applies a standard or built-in format such as 0.00 then a numFmt element isn't written. The <xf> element still contains a numFmtId but it refers to a built-in format that isn't stored in the file.
Number format ids less than 164 (but most often in the range 0-50) represent builtin formats.
Here is a list of some of the built-in formats form the XlsxWriter documentation.

No numFmt in Styles.xml


SQL Server Express 2008 R2 with old Management Studio?

Question: On the same machine with SQL Server 2008 R2 Express installed, can the last stand-alone version of the Management Studio be installed? That would be SQL Server 2008 Management Tools. Or does it have to be the latest version that comes with the R2 installer?
Answer: You can install the old management console side by side with a newer installation, but I'm not quite sure why you would want to. The newer consoles can connect to the older versions (although this may not be the case with expresss, it's been a long time since I used it).
Comment: Just keep in mind that the older studios can *not* connect to the newer SQL instances, only the reverse
Comment: The reason is mostly because the Management Studio that comes with R2 takes over 2GB of disk space to install and I don't have that much free on my test system at the moment.


Why this error: incompatible pointer to integer conversion?

Question: Please have a look at the code, clang is giving me the error "incompatible pointer to integer conversion", why is it happening?
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
    char* name;
    name = malloc (sizeof(char) * 6);
    *name = "david";
    return 0;
}

Answer: Whatever is happening is happening at this line:
*name = "david";

The type of *name would be char, as you are dereferencing the char pointed to by name. The type of "david" is char[6], as it's a string literal of 6 chars (5 + null terminator). An array type decays into a pointer and a char is an integral type; your assignment tries to set a pointer to an integer, hence incompatible pointer to integer conversion.
Even if the left side of the assignment had the right type, you couldn't just copy arrays with the assignment operator. If you want to set name to "david", then you should be using strcpy( name, "david" ).
Answer: In C programming you can never copy/assign the string into a pointer directly like
*name = "david";

You can only copy a string using memcpy() (in built function).To fix the issue replace the line
*name = "david"; with memcpy(name,"david",sizeof("david"));
Comment: sizeof() function returns the size of the string along with terminating null character strlen() will not count the NULL character which will be present at the end of the string.So the Plus one after sizeof("david") is not required.
Comment: You should add +1 to the size for the case when name will contains something else than a bunch of zero: memcpy(name,"david",sizeof("david") + 1);
Comment: Oh yes, you're right.  It has been so many years the last time that I've coded in C that I've now forgotten its basic principles.  Sorry!
Answer: This line:
*name = "david";

should read
name = "david";

*name is synonymous (in this context) with name[0] (i.e. the first character of a string pointed to by the name variable). You want the name variable, not the contents of the pointer, to be assigned to point at the same thing that the string literal "david" is pointing at.
Answer: look here name is not a pointer to character
by using the library function malloc you have made it an array of characters
so you cannot simply point it to any address like a pointer
you have to use library function strcpy(p,"david")
then only it will give you desired results


match a branching path of variable length

Question: I have a graph which looks like this:

Here is the link to the graph in the neo4j console:
http://console.neo4j.org/?id=av3001
Basically, you have two branching paths, of variable length. I want to match the two paths between orange node and yellow nodes. I want to return one row of data for each path, including all traversed nodes. I also want to be able to include different WHERE clauses on different intermediate nodes.
At the end, i need to have a table of data, like this:

a   - b        - c       - d
neo - morpheus - null    - leo
neo - morpheus - trinity - cypher

How could i do that?
I have tried using OPTIONAL MATCH, but i can't get the two rows separately.
I have tried using variable length path, which returns the two paths but doesn't allow me to access and filter intermediate nodes. Plus it returns a list, and not a table of data.
I've seen this question:
Cypher - matching two different possible paths and return both
It's on the same subject but the example is very complex, a more generic solution to this simpler problem is what i'm looking for.
Answer: You can define what your end node by using WHERE statement. So in your case end node has no outgoing relationship. Not sure why you expect a null on return as you said neo - morpheus - null - leo
MATCH p=(n:Person{name:"Neo"})-[*]->(end) where not (end)-->()
RETURN extract(x IN nodes(p) | x.name)

Edit:
may not the the best option as I am not sure how to do this programmatically. If I use UNWIND I get back only one row. So this is a dummy solution
MATCH p=(n{name:"Neo"})-[*]->(end) where not (end)-->()
with nodes(p) as list
return list[0].name,list[1].name,list[2].name,list[3].name

Comment: I need to get rows of data at the end (in table format), not a list. Is there any way to do that?
Answer: You can use Cypher to match a path like this MATCH p=(:a)-[*]->(:d) RETURN p, and p will be a list of nodes/relationships in the path in the order it was traversed. You can apply WHERE to filter the path just like with node matching, and apply any list functions you need to it.
I will add these examples too
// Where on path
MATCH p=(:a)-[*]-(:d) WHERE NONE(n in NODES(p) WHERE n.name="Trinity") WITH NODES(p) as p RETURN p[0], p[1], p[2], p[3]

// Spit path into columns
MATCH p=(:a)-[*]-(:d) WITH NODES(p) as p RETURN p[0], p[1], p[2], p[3]

// Match path, filter on label
MATCH p=(:a)-[*]-(:d) WITH NODES(p) as p RETURN FILTER(n in p WHERE "a" in LABELS(n)) as a, FILTER(n in p WHERE "b" in LABELS(n)) as b, FILTER(n in p WHERE "c" in LABELS(n)) as c, FILTER(n in p WHERE "d" in LABELS(n)) as d

Unfortunately, you HAVE to explicitly set some logic for each column. You can't make dynamic columns (that I know of). In your table example, what is the rule for which column gets 'null'? In the last example, I set each column to be the set of nodes of a label.
Comment: I tried using path, but I want to apply individual filter to different intermediate nodes in the path. I also need to have rows of data at the end, not a list. I am updating my question to make that clearer.
Comment: @FlorentChatterji I added some more examples of using paths. I'm not sure what WHERE logic you want to use. The last example is the closest to what you asked. If you need dynamically generated columns, you will probably have to settle for one column with a list of nodes instead.
Answer: I.m.o. you're asking for extensive post-processing of the results of a simply query (give me all the paths starting from Neo). I say this because :

You state you need to be able to specify specific WHERE clauses for each path (but you don't specify which clauses for which path ... indicating this might be a dynamic thing ?)
You don't know the size of the longest path beforehand ... but you still want the result to be a same-size-for-all-results table. And would any null columns then always be just before the end node ? Why (for that makes no real sense other then convenience) ?
...

Therefore (and again i.m.o.) you need to process the results in a (Java or whatever you prefer) program. There you'll have full control over the resultset and be able to slice and dice as you wish. Cypher (exactly like SQL in fact) can only do so much and it seems that you're going beyond that.
Hope this helps,
Regards,
Tom
P.S. This may seem like an easy opt-out, but look at how simple your query is as compared to the constructs that have to be wrought trying to answer your logic. So ... separate the concerns.


Como preencher setText do TextView a partir de um ArrayList?

Question: Eu recebo um array com itens de interesses e devo setá-los no setText de um determinado TextView.
Quero que apareçam todos os itens deste array, na tela, na horizontal. Em meu xml de layout, somente coloquei 1 textView para receber todos os itens que vierem neste array.
Minha dúvida, tenho que montar um ListView, na horizontal, para receber este array e apresentá-lo na tela? Ou, posso simplesmente pegar os itens e colocá-los na propriedade setText deste TextView?
Segue o código:
@BindView(R.id.txtInterests)
TextView txt_interests;

CommunityPresenter presenter;
UserCommunity selectedUser;
List<String> interest = new ArrayList<String>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        getWindow().setEnterTransition(new Fade());
    }
    setContentView(R.layout.activity_ride_request);

    ButterKnife.bind(this);
    presenter = new CommunityPresenter(this);

    first.setText(presenter.getDay(0));
    second.setText(presenter.getDay(1));
    third.setText(presenter.getDay(2));

    user = new SessionManager();

    selectedUser = CommunityService.i(getContext()).selectedUser;
    reloadView();

    send_offer_request.setOnClickListener(presenter.sendRequestOnClickListener(0));
    send_ask_request.setOnClickListener(presenter.sendRequestOnClickListener(1));

    populateInterests();

}

private void populateInterests() {
    RequestManager.UsersInterests(selectedUser.id, new FutureCallback<String>() {
        @Override
        public void onCompleted(Exception e, String result) {

            //array com os interesses
            interest = new Gson().fromJson(new JsonParser().parse(result).getAsJsonObject().get("data").toString(), new TypeToken<ArrayList<String>>() {
            }.getType());

            txt_interests.setText(); //preencher o TextView com os interesses

        }
    });
}

Comment: Olá Henrique, fica mais fácil te dar uma resposta concreta se você editar sua pergunta e explicar o que exatamente quer apareça em `txt_interests`. Se pode ser qualquer coisa (em qualquer formato) a resposta pode ser simplesmente `txt_interests.setText(interest.toString());` (que vai exibir algo como `[Interesse1, Interesse2, Interesse3]`).
Comment: Editei, mas é basicamente o que estava na pergunta mesmo. Gostaria de saber como pode ser feito para que seja apresentado como textos na tela, ao receber este array com os itens.
Comment: Oi Henrique, veja se a sugestão no comentário acima resolve (acho que foi isso que o Victor quis dizer na resposta dele também). É claro que visualmente uma *List View* com um item para cada interesse é bem diferente de uma *Text View*  com todos os interesses concatenados em uma única String, mas o que é melhor depende da aplicação. Ou sua dúvida é outra?
Comment: @AnthonyAccioly seria uma parte a questão da lógica, resolvida pelo "toString" e qual seria melhor. Mas consegui entender aqui. Pode colocar como resposta que marco. Muito obrigado!
Comment: Oi @Henrique, sem problemas. Acho que as respostas atuais já estão tratando do que eu iria escrever, então fique a vontade para aceitar a que melhor se encaixar ao seu problema (assumindo que ele esteja resolvido)
Answer: De acordo com seu questionamento, vou tentar responder de forma simples baseando nos dados e código que você disponibilizou.
Pelo que percebemos, você declarou uma variável do tipo List<String> cujo nome é interest, que ocasionalmente seriam os interesses que você quer atribuir ao seu TextView.
Para que você capture cada item, é necessário você percorrer toda sua lista. Existem diversas maneiras de você percorrer e capturar elementos de uma lista e uma delas é usar um foreach. Abaixo segue um exemplo bem básico:
String interests = "";
for(String str: interest){
    interests+="\n"+str;
}
txt_interests.setText(interests);

Como de preferência sua, querendo que apareça os itens na horizontal, eu inserir um \n para fazer uma quebra de linha no qual o próximo "interesse" aparecerá uma abaixo do outro.
Atualização
Como nosso amigo ressaltou nos comentário, existe uma discussão antiga que frequentemente aparece no Java que é o uso errado da concatenação de Strings, que pode acarretar numa perda de performance e trashing de memória.
O uso do operador + parece inocente, mas o código gerado produz algumas surpresas. Usando um StringBuilder para concatenação pode na verdade produzir um código que é significativamente mais rápido do que usando um String. Segue abaixo:
StringBuilder interests = new StringBuilder();
for(String str: interest){
    interests.append("\n").append(str);
}
txt_interests.setText(interests);

Para saber mais detalhes, você pode ler este artigo que fala sobre as diferenças entre String, StringBuilder e StringBuffer em Java.
Comment: Oi seamusd, boa resposta. O único detalhe de implementação seria a concatenação dentro de um laço. Enquanto o compilador [tenta otimizar](http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.18.1) esse tipo de coisa, vale a pena ser explícito e usar um `StringBuilder`.
Answer: Se você quer adicionar tudo em um TextView só, é só concatenar as informações da sua lista e adicionar no setText.
Comment: Não entendi sua resposta. Eu quero colocar no setText do textView. Eu teria que criar uma lista, personalizada?


Get category product with minimal price of product in each category (Django querysets)

Question: I want to get from database only 3 categories with lowest price product in each category so i tried to do this
Category.objects.get(id=1).category_product.all().values('price').order_by('price')[0]

Category.objects.get(id=2).category_product.all().values('price').order_by('price')[0]

Category.objects.get(id=3).category_product.all().values('price').order_by('price')[0]

How to simplify this queryset, get three categories with lowest price of product in each category? Get with one request
class Product(models.Model):
    name = models.CharField(max_length=255)
    category = models.ForeignKey(Category, on_delete=models.PROTECT, null=True, related_name='category_product')

class Category(models.Model):
    name = models.CharField(max_length=255)
    slug = models.SlugField(unique=True)
    image = models.ImageField(upload_to='images', null=True, blank=True)

Comment: is the price field defined on the product model?
Comment: yes i just removed sorry
Answer: Category.objects.filter(id__in=[1,2,3]).category_product.order_by('price').values('id', 'price')[:3]

Comment: Generally, answers are much more helpful if they include an explanation of what the code is intended to do, and why that solves the problem without introducing others.


Add a view multiple times in same container programmatically

Question: The loop below works if run once (n = 1) but craches for multiple execution (n > 1).
IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first. at line "containerLL.addView(divider);"
There is other views being created using "new" within this loop as well but not relevant to the problem at hand.
I am not sure if I need to make a "new" RelativeLayout
every time or what would be the correct way to fix it.
Thank you
divider.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/divider_parent"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
    android:id="@+id/plan_divider"
    android:layout_width="match_parent"
    android:layout_height="2dp"
    android:background="?android:attr/listDivider" />

LinearLayout containerLL = (LinearLayout) activity.findViewById(mContainerViewId);
for(int i = 0; i<n ; i++){
    LayoutInflater li = LayoutInflater.from(activity);
    RelativeLayout rl = (RelativeLayout) activity.findViewById(R.id.divider_parent);
    View divider = li.inflate(R.layout.divider, rl);
    containerLL.addView(divider);
}

Answer: Try this.
LinearLayout containerLL = (LinearLayout) activity.findViewById(mContainerViewId);
for(int i = 0; i<n ; i++){
    LayoutInflater li = LayoutInflater.from(activity);
    View divider = li.inflate(R.layout.divider, null, false);
    containerLL.addView(divider);
}

Answer:
I am not sure if I need to make a "new" RelativeLayout every time

No, your problem is that you made divider a child of rl. It cannot be a child of rl and a child of containerLL. It has to be a child of one or the other.
Also, do not use LayoutInflater.from(activity). Use activity.getLayoutInflater(). Otherwise, your styles and themes may get messed up.


How prove this sequence converge $\{x_{n}\}=2^{\frac{2^{n}-1}{2^{n}}}$

Question: i need help with this exercise i need prove the serie
$\{x_{n}\}=2^{\frac{2^{n}-1}{2^{n}}}$ Converge.
I know for limits, this
$lim_{n\rightarrow\infty}2^{\frac{2^{n}-1}{2^{n}}}=2$
Now, i need prove that result and i finish my exercise.
I try this:
Let $\epsilon>0$, $\exists N\in\mathbb{N}$ such that $n>N$ then $|x_{n}-2|<\epsilon$
Now i want find that $N$
I try this: $|2^{\frac{2^{n}-1}{2^{n}}}-2|=|2^{1-\frac{1}{2^{n}}}-2|=|2\times2^{-\frac{1}{2^{n}}}-2|=|2(2^{-\frac{1}{2^{n}}}-1)|=2|2^{-\frac{1}{2^{n}}}-1|=2|\frac{1}{2^{\frac{1}{2^{n}}}}-1|=2(1-\frac{1}{2^{\frac{1}{2^{n}}}})$ But i'm stuck in that part, can someone help me?
Comment: Examine first the convergence of $\log_{2}(x_{m})$.  Now, $\log_{2}$ is a continuous function on the positive abscissa semiaxis.
Answer: I'm going to try this a bit different than usual. It is trivial that $2^{(2^n-1)/2^n} > 0$, because the statement $2^n > 0$ holds for all $ n \in \mathbb{R}$. We now show that the sequence is monotonically increasing for positive $n$, i.e. that
$$2^{(2^{n+1}-1)/2^{n+1}}>2^{(2^n-1/2)/2^n}$$
It is now clear that
$$2^n-1/2 > 2^n - 1 \implies \frac{2^n-1/2}{2^n} > \frac{2^n-1}{2^n}$$
and since $2^n$ is monotonically increasing for $n>0$, so is your function. Since we have $\lim_{n \to \infty} f(n) = 2$, our function must clearly be bounded by $2$ for positive $n$
Comment: I think you should drop limit. Monotonic [and bounded] sequences in $\mathbb{R}$ converge.


How to determine which Note is Scale Degree 7 in a key (for example, A Major)?

Question: What note is scale degree 7 in a key? For example, in A Major, it seems to me it might be A but I do not know.
How do you determine which note corresponds to the 7th scale degree.  What about the other notes and their corresponding degree?
Comment: It cannot be A, as A is the root note. It will always be the note prior to the root. This has already been marked down, as it appears there has been little attempt to find a readily available answer.
Comment: https://en.wikipedia.org/wiki/Major_scale
Comment: @Tim Just to be clear, when you say "it will always be the *note* prior to the root" -- you mean *half step* (or *semitone*), correct? For example in A maj I would regard the previous _note_ to A as G, whereas the previous _half step_ is G#.
Comment: @JYelton - why would the previous note to A be G? G isn't in the A major scale or key. G# is.
Comment: I'm just saying that "note" could be vague. Some might think that "note" refers to the letter (G preceding A) rather than the sharps and flats, etc. Or maybe I'm just confusing things.
Answer: First of all, a question like this can be easily answered with a simple google search.  If you search for A-Major scale on line, one of the results will be:
Basic Music Theory dot com A Major Scale
The following two images from that site show the entire A-Major Scale. The first shows the notes on the piano keyboard and the second shows the notes on the treble clef in standard music notation.

The formula for all major scales for the intervals between notes is
W W H W W W H  Which can also be written out as whole whole half, whole whole whole half.
You always start on the root note and count that as the first scale degree (# 1).  Then you go up the "chromatic scale" (which consists of all notes playable on a piano keyboard) by one whole step to get to the next note in the scale which is the second scale degree.  One whole step is equal to two half steps.  A half step is represented by each key on a piano keyboard (black keys included).
So in A Major you start on A which is the 1 degree and go one whole step (a black key and a white key) to land on B which is the second scale degree.  From B you again go a whole step (one white key and one black key) and you land on a black key which is C#.  Next in the major scale formula is a half step because now we are on the first H in our formula W W H W W W H.  A half step from C# is to the adjoining key which is a white key and is a D (4th scale degree).  This process is repeated (following the whole half formula) until we get back to the root note of A which is the 8th scale degree if you will.
All Major scales will start on the root note as the first scale degree and follow this same formula.  A piano keyboard is useful in visualizing the whole (two keys) and half (the next key to the right) steps.
Minor keys have their own formula which differs from the major scale formula.
If you forget this, simply google whatever scale you need to know about and you will find your answer there.
Comment: @FernandoGabrieli I think you are confusing chords and scales.  In chord notation B7, C7, G7 etc.  is actually the way to describe a "Dominant 7th" chord which is commonly used in songs written in major keys.  To play Dominant 7th chord you add a "flattened" 7th degree to the scale of the root of the major chord.  In the case of a C7 chord, a C Major chord would have C as the root note followed by the 3rd and 5th notes of the scale.  So a C chord is C E G.  To make this chord a C7 you find the 7th note in the C scale which is B and then flatten it to Bb (which happens to be the same as A#).
Comment: @FernandoGabrieli  You may be confusing a "half step"  with "flat".  In Western Music an octave is divided into 12.  But there are only 7 "whole notes" A B C D E F and G.  There are 5 "half notes".  7 plus 5 = 12.  In a major scale the tones between the root note & the next note are one whole step. All the keys (both black and white) on a keyboard count as a step and when you jump the adjacent key to get to the key after the adjacent key that is a whole step.  Since there is no black key to jump between B & C that is only a half step.  But it's not flat in the key of C Major.
Comment: The whole point of a Google search is to land on _this_ page to answer the question, which is exactly how I just got here. Whatever resources are on the web, the goal of StackExchange (to me) is to be a _better_ resource. I prefer your answer to the one you linked.
Comment: @JYelton Good point.  One time my daughter's boyfriend was doing a Google Search for something and found one of my SE Answers and he said it was the number one result that popped up from his query.  I was only trying to let the OP know that Google can be a resource for any questions the OP might have along these lines.  But I was happy to share my explanation as well.  And add thereby add to the body of information available in a Google search.  I'm glad you liked my answer.
Comment: So, being in A major, G# is the 7th degree. Now, if a song has say C#7, does that mean that i would play C# chord+ G#? and B7 would be B chord + G# ? thanks in advance
Comment: @RockinCowboy you always need to make the 7th flat? I ask because if i take say C major, it does not have any flats in it. The 7th degree would always be natural by just counting steps through the notes.


Reference request: Distribution of a maximum Gaussian RV

Question: when searching for the distribution of the extreme value of a large set of iid Gaussian RVs, I stumbled upon this answer by Sasha, which gave more accurate results than the approximation given in Fisher & Tippett.
There was no reference for the source of Sahsa's approximation, and it would be helpful if someone could direct me to some book or article that derives it.
Answer: Sasha's answer cites
http://reference.wolfram.com/language/ref/ExtremeValueDistribution.html#6764486
The example there starting with the text "Construct an approximation for the distribution of maximum value in a normal sample of size $n$:" is the computation shown in her answer.
What more reference are you wanting?
Comment: The cited page doesn't give the derivation of the constants
$\mu_n = \Phi^{-1}\left(1-\frac{1}{n} \right) \qquad \qquad
   \sigma_n = \Phi^{-1}\left(1-\frac{1}{n} \cdot \mathrm{e}^{-1}\right)- \Phi^{-1}\left(1-\frac{1}{n} \right)$  it simply states the final result and show that it works.
Comment: These are ancient results.  See [Gumbel 1935](http://archive.numdam.org/ARCHIVE/AIHP/AIHP_1935__5_2/AIHP_1935__5_2_115_0/AIHP_1935__5_2_115_0.pdf), eqn (14'), et seq.
Comment: Of course. How can one not be familiar with such elementary paper, published in a french statistics journal in 1935?
Comment: @avishayantman : Or, as one can find immediately from the linked Wikipedia page, *the* paper by Gumbel introducing th Gumbel distribution, the $\xi = 0$ case of the [generalized extreme value distribution](https://en.wikipedia.org/wiki/Generalized_extreme_value_distribution).  The referenced page also introduces the $\Phi^{-1}(1 - \frac{1}{n})$ and the GEVD page, Sasha's $F_{EV}$.


Uniform convergence of convex functions on unbounded set

Question: Let $f_n:[0,\infty[\,\to\mathbb{R}$ be a convex decreasing functions of $x$, for all $n\in\mathbb{N}$.
Suppose that there exists $\lim_{n\to\infty}\lim_{x\to\infty}f_n(x)=\lambda$.
Suppose also that there exists $\lim_{n\to\infty}f_n(x)=f(x)$.
Can I interchange the limits and say that $\lim_{x\to\infty}f(x)=\lambda$ ?
I know that every convergent sequence of convex functions on an open interval is uniformly convergent on compact sub-intervals. Here can I do something to deal with the fact that $x\to\infty$? Maybe is it possible to conclude adding some hypothesis?
Answer: You cannot interchange the limits here. A counterexample is $f_n(x) = \exp(-x/n)$,
which gives you $\lim_{x\to\infty} f_n(x) = 0$, but $\lim_{n\to\infty} f_n(x) = 1$.
This counterexample also shows that even with very nice functions (strictly convex with derivatives of all orders jointly bounded), uniform
convergence cannot be concluded if the domain is not (totally) bounded. For
that reason, I am inclined to say that the fact that the functions are convex
is probably of no use at all.
Comment: Thank you for the couterexample! Probably convexity is really not useful in this case
Comment: But I think a uniform bound for the first derivative (uniform both with respect to $n$ and to $x$) would be sufficient to conclude
Comment: @user118866: The counterexample already has $-1 \le f_n'(x) < 0$.


Unsetting a field before hook_form_alter

Question: I have a field collection with two entity reference fields that I keep hidden on a node creation form. The reference fields in the hidden field collection are slowing down the page load time. I need to block the field collection from rendering at all. From what I understand it needs to happen before hook form alter. See Question - Does unset($form['field']); in hook_form_alter stop entity reference views select list queries from running?. Any help would really be appreciated!
Comment: _The reference fields in the hidden field collection are slowing down the page load time_ I'm not sure why you'd think that is being caused by rendering? It'll be caused by the database queries (incessant joining). The only way to avoid those is to detach the field from whatever entity it's attached to. Field collection is known for its performance problems, I've yet to come across a use case where creating a custom compound field isn't more appropriate, and a lot faster
Comment: Thanks for the response Clive - I appreciate the help. I understand how the database queries are slowing things down. Is there any approach I can use to detach the field from the entity it's attached to before the node add form is built? The question I referenced suggests that queries might be stopped via hook_field_attach_form. Please excuse my ignorance - I am relatively new to programming.
Comment: Sorry, by detach I meant actually remove the field from the entity altogether. There might be a simple hack but I don't know it - fields and entities are pretty configurable but I'm not sure where you'd hook into to stop a particular field from loading data in a particular context (either field_attach_form() or field_attach_load() in this case, probably the former but I'm not 100%)
Comment: I can think of one (rather nasty) hack actually...you could subclass [`FieldCollectionItemEntity`](http://drupalcontrib.org/api/drupal/contributions!field_collection!field_collection.module/class/FieldCollectionItemEntity/7) and override the load/attach functions to exclude certain operations in certain contexts, then use [`hook_entity_info_alter()`](https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_entity_info_alter/7) to update the entity class for the `field_collection_item` entity. As I say, rather nasty, but might be worth a look if you get desperate
Answer: In case this helps anyone - the hidden node reference fields that I have been using were having their lists of selectable nodes generated by views. I ended up using hook_views_query_alter to stop the view query from being run. Here's the code I put into my custom module:
<code>/**
 * Implements hook_views_query_alter().
 *
 * Disables node reference views. This drammatically
 * speeds up performance.
 */
 function mymodule_views_query_alter(&$view, &$query) {
  if ($view->name == "my_view") {
    $view->executed = TRUE;
  }
  if ($view->name == "my_view2") {
    $view->executed = TRUE;
  }
 }
</code>


extractText returns blank text

Question: I have followed the documentation, getIsEncrypted and other attribute is working but extractText() shows blank str.
<code>import PyPDF2 as pPDF

def extract_pdf():
    pdf_file_pointer = open('example/pdf/sample.com', 'rb')
    pdf_file_obj = pPDF.PdfFileReader(pdf_file_pointer)

    page_1 = pdf_file_obj.getPage(1)
    print(page_1.extractText())

extract_pdf()
</code>
Here is a link of pdf file I am working. I want to extract text of the pdf. https://drive.google.com/file/d/1b8M0fuI1GV1zeDYWqIcA1vCcLghb4gXm/view?usp=sharing
Comment: I am having the same problem, however in my case the return value is '\n\n\n\n\n'
Comment: Please try [this library](https://pypi.org/project/tika/) . From my experience this is the best library to read pdf. Only drawback is that you need Java to use it.
Answer: PyPDF2 received lots of improvements in 2022.
Additionally, the project moved back to pypdf.
Upgrade your code and likely it will work :-)
Comment: Thanks for your suggestion. I will give pypdf a shot in next projects.

extractText returns blank text


MYSQL UPDATE with LIMIT and ORDER BY

Question: so I was reading about UPDATE with LIMIT and how it doesnt really return what you want.
Ive been running this statement, and it seems to be working.  But Im worried when my dataset grows, and I go into production if this query will stop working.
Could anyone tell me what is a better way to select a certain batch, and update.
I've read a lot about that it only works if you sort by ID.  But in my case I want to order by Assign_count.
Here's my query...
UPDATE leads SET assign_date='".date('Y-m-d')."',status='ASSIGNED'
   WHERE city='".$city."' AND status='NEW'
   ORDER BY assign_count ASC LIMIT 40");

I'm ordering by the assign_count, and limiting it to 40.  Will this actually select the leads I want to be selecting??  Just curious.  After reading all about UPDATE with LIMIT.  I'm kinda scared that it won't select what I want.  Even though it seems to be working right now on a little bit of data.
Comment: What your problem? Your query looking fine
Comment: @ThinkkSo  thats exactly what I want.  So is this query fine then?  Can I leave it as is??  The answer below mentions something about row count only.  Which I keep reading about...Im just not too sure.
Comment: @KyleK what is the type of your mysql engine
Comment: @KyleK actually now that i remember you have to use `row count` so your code wont break
Comment: this is what you need `UPDATE leads SET assign_date='".date('Y-m-d')."',status='ASSIGNED' WHERE city='".$city."' AND status='NEW' ORDER BY assign_count ASC LIMIT 0,40`
Comment: Are you sure?? Why is it working fine how it is??  What exactly does the 0, do?  Sorry for the newb questions
Comment: it starts from the index 0 to 40 and if it was 10 40 it will skip the first 10 and start at 11 to 40
Comment: so would 40 without the 0 work?? Cuz it seems to work right now.  Just wondering if it is better to make it 0,40 or just leave it as LIMIT 40
Comment: well i would advice you to do 0, 40 for better practice but you can also go your way and do LIMIT 40 if it still works
Answer:    UPDATE leads SET assign_date='".date('Y-m-d')."',status='ASSIGNED' WHERE city='".$city."' AND status='NEW' ORDER BY assign_count ASC LIMIT 0,10

LIMIT can be used with UPDATE but with the row count only

MYSQL UPDATE with LIMIT and ORDER BY


Newton-Raphson Method.

Question: I have to find a real root of the equation $x=\ e^{-x}$ ,  using the Newton-Raphson Method.
I solved the example writing the function in the form $f(x)=x -\ e^{-x}=0$ which is straightforward and i found the approximates after 3 iteration and confirm it in 4th iteration.
But in the book from which i am solving exercise, they rewrite the equation in the form $f(x)=x\ e^{x}-1=0$. Also here the solution is obtained after 3 iteration.
Is there any advantage if i rewrite the function , that is , is there any matter of convergence here?
Answer: Let's look at the iterations you get from each.
With $f(x) = x - e^{-x}$, you get
$$F(x) = x - \frac{f(x)}{f'(x)} = x - \frac{x-e^{-x}}{1+e^{-x}} = \frac{x + xe^{-x} - x + e^{-x}}{1+e^{-x}} = \frac{x+1}{e^x+1}.$$
That's a nice function, defined on all of $\mathbb{R}$, gets you close to the solution real fast when you start at a non-negative $x_0$, but is not so good for negative $x$, then it approaches the fixed point slowly at first.
With $g(x) = xe^x - 1$, you get
$$G(x) = x - \frac{g(x)}{g'(x)} = x - \frac{xe^x-1}{(x+1)e^x} = \frac{x^2e^x+1}{(x+1)e^x} = \frac{x^2+e^{-x}}{x+1}.$$
That function has a pole in $-1$, and $G(x) < -1$ for $x < -1$, so doesn't reach the fixed point from there. For large positive $x$, it doesn't approach the fixed point fast (basically, it's $x \mapsto \frac{x}{x+1}\cdot x$ there).
So looking at the global behaviour, your choice behaves much better.
Now, for the local behaviour near the fixed point, the Newton iteration roughly behaves like
$$\alpha + \delta \mapsto \alpha + \frac{f''(\alpha)}{2f'(\alpha)}\delta^2$$
when $f'$ doesn't vanish in the zero of $f$, as is the case here, so let's look at the corresponding quotient for the two candidates.
$$\begin{align}
\frac{g''(\alpha)}{2g'(\alpha)} &= \frac{(\alpha+2)e^\alpha}{2(\alpha+1)e^\alpha} = \frac{\alpha + 2}{2(\alpha+1)} = \frac12 + \frac{1}{2(\alpha+1)}\\
\frac{f''(\alpha)}{2f'(\alpha)} &= \frac{-e^{-\alpha}}{2(1+e^{-\alpha})} = \frac{-\alpha}{2(1+\alpha)} = \frac{1}{2(\alpha+1)} - \frac12
\end{align}$$
using $e^{-\alpha} = \alpha$ for the latter.
So $G$ approaches the fixed point from above, while $F$ approaches it from below ($f''(\alpha) < 0 < f'(\alpha)$), and the factor of the square has smaller absolute value for $F$, that means the convergence of $F$ is faster near the fixed point $\alpha$ (but that doesn't matter much against the quadratic convergence, nevertheless).
So, altogether, yours was the better choice globally (converges to the solution from all starting points), and locally (converges faster near the fixed point).
Comment: Very enlightening solution. It makes me wonder what the author of the textbook was thinking :)
Comment: Probably the author didn't like $e^{-x}$ and preferred $e^x$. If you start somewhat near the solution, it doesn't make much difference anyway. There's a giveaway that $x-e^{-x}$ may be nicer: that one is concave (globally), while $xe^x -1$ switches between being concave and convex. Also $f'(x) > 0$ always, while $g'$ has a zero.

Newton-Raphson Method.


getting multiple class selectors for select in jQuery

Question: I'm trying to get all select elements in a given div, even though they have different class names. It looks like this:

    <select class="myclass">...</select>
    <select class="myotherclass">...</select>

I'd like to get all the selects with myclass or myotherclass. I've tried several ways but can't get it right.
I've tried variations of the following:
$.each($('[#mydiv select.myclass][#mydiv select.myotherclass]'), function(){ // handle stuff
$.each($('#mydiv select.myclass select.myotherclass'), function(){ // handle stuff
$.each($('#mydiv select.myclass myotherclass'), function(){ // handle stuff

and others, but I can't seem to get both selects into my element selection.
Comment: Have you tried $('#mydiv select').each()? You can get the class attribute as you loop...
Answer: Perhaps
$('#mydiv select.myclass, #mydiv select.myotherclass')

Answer: $.each($("#mydiv .myclass, #mydiv .myotherclass"), function(){ // handle stuff });

Comment: Separate calls to `$()` and `$.each` is inefficient
Comment: WTF! I was quoting the example given, the topic here is how to SELECT multiple classes
Comment: if this method is inefficient, is there a more effective way to accomplish the same thing? Thanks
Comment: Probably **$("#mydiv").find(".myclass, .myotherclass").each(function(){...})**. The difference is you first find **#mydiv** on the document and then perform 2 mini searches to it's children (instead of 2 at document level). That's a micro optimization only noticeable on large documents (browsers index the 'id' of the elements so it's fast anyway)
Comment: I'm not that sure of what @ExplosionPills says about calling **$()** and **$.each** is inefficient [citation needed](http://imgs.xkcd.com/comics/wikipedian_protester.png) because **$.each** is handling just the iteration and of a given set of elements. [In the docs](http://api.jquery.com/id-selector/#entry-longdesc) it reads "As always, remember that as a developer, your time is typically the most valuable resource. Do not focus on optimization of selector speed unless it is clear that performance needs to be improved."
Comment: @Xocoatzin it's faster to type `$().each` than it is to type `$.each($())`
Comment: @ExplosionPills I can't believe you down-voted me because **$.each($(),function(){})** is larger than **$().each(function(){})** by JUST 2 CHARs and typed on a different order. But you are right, you save some 100ms once in a lifetime by doing that.
Comment: @Xocoatzin it's also less performant and shows a lack of understanding of how the jQuery collection and `.each` work.  Also, your answer was a duplicate.
Comment: @ExplosionPills [Citation needed](http://imgs.xkcd.com/comics/wikipedian_protester.png)
Answer: I think it works with
$('#mydiv select.myclass, #mydiv select.myotherclass')

as in Css Selectors
Comment: Does not use `#mydiv` as requeseted
Answer: Try this
JS CODE
$('#mydiv select').each(function(){
 console.log($(this));
});

DEMO
Comment: @julio is that efficient with what you want..?
Comment: This also effective $('#mydiv select.myclass, #mydiv select.myotherclass') as for the selection different classes are separated by a comma.


Adding a Field 'Name on Credit Card' to Product Payment Page

Question: I'd like to add a field called 'Name on Credit Card' to the product payment form on my site but I can't figure out how to add fields to that form. I'm using Commerce and the PayPal WPP module. The default fields for the payment page include only cc number, cc type (visa, etc.), csv, and expiration date.
Anyone know how to add a field to that payment form?
Answer: You'll need to implement some Commerce Payment form builder callback function within a custom module, in order to alter the existing form that PayPal WPP provides.
The payment form is generated using this callback:
CALLBACK_commerce_payment_method_submit_form
You will need to create a custom form building callback function, and then use a hook to change the module's form building callback function name.
Unfortunately I'm not sure off hand which hook you need to use, but the following links could guide you in the right direction:

HOOK_form_alter
commerce_payment.api.php

Whatever you do, don't edit the PayPal WPP module directly, but you probably already know that.
EDIT
See line 182 of commerce_paypal_wpp.module for the form building callback you need to replicate and change in a custom module.
EDIT
I just found the correct hook for you to implement, in order to point the payment method to use your custom CALLBACK function. It comes from commerce_payment.api.php. See extract from module function comments below (line 129):
<code>callbacks (optional): an array of callback function names for the various
types of callback required for all the payment method operations, arguments
per callback in parentheses:
</code>
hook_commerce_payment_method_info_alter
Comment: Thank you. This is new to me. I'm already using hook_form_alter to modify the overall form (the payment method form snippet you speak of is also appearing on this main checkout form). So is it just a matter of adding the new field to the form with hook_form_alter() and then also calling and renaming the callback function somewhere in this same custom module file? What would I call the CALLBACK function? 'CALLBACK_function-name' or do I make up some other name to replace CALLBACK with? how do I link them to make sure hook_form_alter calls the new CALLBACK function? Sorry, new to this aspect.
Comment: You're almost there in your approach :) You don't need to add the new field via hook_form_alter, but rather within your custom CALLBACK function.

I was suggesting to try use hook_form_alter to change the callback function name used by paypal_wpp, but it might not be the right place to change it.
Comment: Actually just found the right hook for you to use to change the callback function. See edit #2 above.
Comment: Ok, I've made an attempt. Can you please give me some guidance on how to improve this? I made a new thread here: https://drupal.stackexchange.com/questions/192333/how-to-correctly-edit-a-form-callback-to-add-fields-to-a-product-form
Comment: will try my best to get to it ASAP, busy day at the office :)


Unable to align text to right of imageview android layout xml

Question: I am trying to create layout like below in android:

But my problem is I am unable to  add textbelow  the image or on the right hand side of imageview. If I wrap ImageView and textview in a LinearLayout the then the whole view shrinks. Should I be using TableLayout?
My current layout xml is like below:
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:layout_below="@id/my_recycler_view"
    android:layout_margin="30dp">

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:orientation="vertical"
        android:layout_weight="1"

        >

        <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/vwImageAndClassroom"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center"
            >

            <ImageView
                android:id="@+id/img_room"
                android:layout_width="fill_parent"
                android:layout_height="100dp"
                android:layout_gravity="center_horizontal"
                android:contentDescription="@string/coverimage_contentdescription"
                android:scaleType="fitCenter"
                android:src="@drawable/comm_book_icon"

                />

            <TextView
                android:id="@+id/tv_emp_name"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal|center_vertical"
                android:textSize="12dp"
                android:textStyle="bold"
                android:textAllCaps="true"
                android:layout_below="@id/img_room"
                android:layout_marginBottom="20dp"
                android:gravity="center_horizontal"
                android:text="TEXT 1"

                />
        </RelativeLayout>

    </LinearLayout>

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:orientation="vertical"
        android:layout_weight="1"

        >

        <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/vwImageAndClassroom2"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center"
            >

            <ImageView
                android:id="@+id/img_room2"
                android:layout_width="fill_parent"
                android:layout_height="100dp"
                android:layout_gravity="center_horizontal"
                android:contentDescription="@string/coverimage_contentdescription"
                android:scaleType="fitCenter"
                android:src="@drawable/visitor_book_icon"

                />

            <TextView
                android:id="@+id/tv_emp_name2"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal|center_vertical"
                android:textSize="12dp"
                android:textStyle="bold"
                android:textAllCaps="true"
                android:layout_below="@id/img_room2"
                android:layout_marginBottom="20dp"
                android:gravity="center_horizontal"
                android:text="TEXT 2"

                />
        </RelativeLayout>

    </LinearLayout>

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:orientation="vertical"
        android:layout_weight="1"

        >

        <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/vwImageAndClassroom3"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center"
            >

            <ImageView
                android:id="@+id/img_room3"
                android:layout_width="fill_parent"
                android:layout_height="100dp"
                android:layout_gravity="center_horizontal"
                android:contentDescription="@string/coverimage_contentdescription"
                android:scaleType="fitCenter"
                android:src="@drawable/visitor_book_icon"

                />

            <TextView
                android:id="@+id/tv_emp_name3"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal|center_vertical"
                android:textSize="12dp"
                android:textStyle="bold"
                android:textAllCaps="true"
                android:layout_below="@id/img_room3"
                android:layout_marginBottom="20dp"
                android:gravity="center_horizontal"
                android:text="TEXT 3"

                />
        </RelativeLayout>

    </LinearLayout>

</LinearLayout>

Comment: please show the output screen of this xml design of yours above mentioned picture does not correspond the information very well with provided xml
Comment: @snowflakes which one? Or all at once?
Comment: @Rizwanatta Thank you please see my updated xml ..it is almost what I am trying to achieve. The only thing that is not working is ability to add text to the right of the third imageview as per the illustration.
Answer: Hope this will help you and you will find your solutions from this xml code. I just modify some of your code
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/image1"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:src="@android:drawable/ic_search_category_default"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This Right side text 1"/>

</LinearLayout>

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <ImageView

        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:src="@android:drawable/ic_search_category_default"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This Right side text 1"/>

</LinearLayout>

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:src="@android:drawable/ic_search_category_default"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This Right side text 1"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_gravity="center">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="This is under layout text"/>
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="This is under layout text"/>

    </LinearLayout>

</LinearLayout>

Comment: thank you please have a look at my updated layout in my question. It is almost what I am trying to achieve except I just want two more textfields align to the right of the imageview (img_room3)
Comment: Please check the latest update. Hope this will be okay
Answer: Have placeholder views where text is not required.

  <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="100dp"
    android:orientation="horizontal">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1">

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@color/next_green" />

        <View
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1">

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@color/next_green" />

        <View
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1">

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@color/next_green" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:text="text"/>
    </LinearLayout>
</LinearLayout>

Answer: I did exactly what you want
Open image
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">

<ImageView
    android:id="@+id/imageView"
    android:layout_width="300dp"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    app:srcCompat="@android:drawable/btn_dialog" />

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/imageView3"
        android:layout_width="300dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        app:srcCompat="@android:drawable/btn_dialog" />

</LinearLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        app:srcCompat="@android:drawable/btn_dialog" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:orientation="vertical">

        <TextView
            android:id="@+id/textView5"
            android:layout_width="match_parent"
            android:layout_height="15dp"
            android:text="Some text" />

        <TextView
            android:id="@+id/textView6"
            android:layout_width="match_parent"
            android:layout_height="15dp"
            android:text="Some text" />
    </LinearLayout>

</LinearLayout>
</LinearLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/textView7"
        android:layout_width="300dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Some text"
        app:srcCompat="@android:drawable/btn_dialog" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/textView8"
            android:layout_width="300dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:text="Some text"
            app:srcCompat="@android:drawable/btn_dialog" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/textView9"
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Some text"
            app:srcCompat="@android:drawable/btn_dialog" />

        </LinearLayout>

    </LinearLayout>
    </LinearLayout>


Rank of Elliptic Curve, $Y^2=x^3+px$ where $p$ is prime is either $0,1,2$

Question: I am following book "Rational Points on Elliptic Curves" by Silverman-Tate(basic version not the "The Arithmetic of Elliptic Curves" by Silverman-Tate) And I am trying to solve for cubic curve, $y^2=x^3+px$ where $p$ is prime
1) Rank of the curve is $0,1$ or$ 2$.
Using the standard methods described in that book.
I am considering various equations of the form $N^2 = b1M^4+b2e^4$ where $b_1.b_2=b$ to check if there is any solutions modulo $p$ and considering quadratic residue modulo $p$.
I know that this same questions were asked previously but currently I am not familiar with the content of "The Arithmetic of Elliptic Curves" by Silverman-Tate)". So I need to prove what is currently in "Rational Points on Elliptic Curves" (by Silverman-Tate).
Any kind of help is much appreciated.
Comment: Welcome to MSE. For some basic information about writing mathematics at this site see, *e.g.*, [basic help on mathjax notation](/help/notation), [mathjax tutorial and quick reference](//math.meta.stackexchange.com/q/5020), [main meta site math tutorial](//meta.stackexchange.com/a/70559) and [equation editing how-to](//math.meta.stackexchange.com/q/1773).
Answer: This is proved in Silverman's book "The Arithmetic of Elliptic Curves" on page 311. The rank $r(E)$ of $E:y^2=x^3+px$ for $p$ prime is given as follows:
$$
r(E)= \begin{cases} 0, \text{ if } p\equiv 7,11 \bmod 16 \\
 0 \text{ or }1, \text{ if } p\equiv 3,5,13,15 \bmod 16 \\
 0 \text{ or }1 \text{ or }2, \text{ if } p\equiv 1,9 \bmod 16
\end{cases}
$$
You can compare with the book by Silverman-Tate, in order to see which theorems are available.
Edit. After searching I found the question you have mentioned:
Rank of the elliptic curve $y^2=x^3+px$


ASP.NET MVC installation on Windows Server 2008 R2

Question: When I install ASP.NET MVC 3 RTM on Windows Server 2008 R2 (Web server edition) will I also be able to run MVC 2 and MVC 1 web applications without installing them or do I need to install all of them separately?
Answer: You would need to install all 3 separately. If you want to avoid installing them altogether, you could bin deploy your applications. It's easy.
For mvc 3 with razor: http://www.hanselman.com/blog/BINDeployingASPNETMVC3WithRazorToAWindowsServerWithoutMVCInstalled.aspx
For mvc 1 and 2:
http://haacked.com/archive/2008/11/03/bin-deploy-aspnetmvc.aspx


Given the sample triangle below and the conditions, find the hypotenuse of the triangle

Question: Given the sample triangle below and the conditions $b=\frac53$ and $a=16$, find the hypotenuse of the triangle.
Comment: Why do you write $B=5/3$? Is this $b=5/3$? or anything else?
Comment: HINT: $c=\sqrt[2]{a^2+b^2}$
Answer: It's a right angled triangle so you can use Pythagorean Theorem.
$$a^2 + b^2 = c^2$$
$$16^2 + 5^2/3^2 = c^2$$
$$256 + 25/9 = c^2$$
$$258 + 7/9 = c^2$$
$$\sqrt{258 + 7/9} = c$$
$$c \approx 16.087$$
Answer: We initially use the tan function: $\tan \left( \frac{5}{3} \right) = \frac{b}{a} = \frac{b}{16}$, so $b = 16 \tan(\frac{5}{3})$.
You can then directly apply Pythagoras' Theorem, so: $c^2 = 16^2 + (16 \tan(\frac{5}{3}))^2 = 16^2 (1+ (\tan \left(\frac{5}{3} \right) )^2)$, and then $c = 16 \sqrt{1+ (\tan \left(\frac{5}{3} \right) )^2 )}$.


Why do we put this term to the power of n/2 instead of n in this MLE?

Question: Let say we want the estimator of something within the normal distribution. Let's take $\sigma^2$ as an example.
We would therefore write $$L(\sigma^2) = \prod_{i=1}^n \dfrac{1}{\sqrt{2\pi \sigma^2}} e^{\frac{- (x - \mu)^2}{2\sigma^2}}$$
When trying to extract terms outside the product symbol we get this: $$\left(\frac{1}{\sqrt{2\pi}}\right)^n \left(\frac{1}{\sigma^2} \right)^{n/2} \prod_{i=1}^n e^{ \frac{-1}{2} \cdot \frac{(x - \mu)^2}{\sigma^2}}$$
My question is why when this $\dfrac{1}{\sigma^2}$ is put out of the product symbol do we make it to the power of $n/2$ instead of $n$ in contrast to what we did to $\dfrac{1}{\sqrt{2\pi}}$?
Comment: That's the same thing. Because $\sqrt{2\pi}^n = (2\pi)^{n/2}$ and $\sqrt{\sigma^2}^n = (\sigma^2)^{n/2}=\sigma^n$. Just arbitrary choices between which one to write, depending only on the person writing.
Comment: Sorry for not seeing it the teacher just skipped a bunch of steps and I was confused. Thank you for the answer.
Comment: No worries at all.
Answer: You could have written $\left(\frac{1}{\sqrt{2\pi \sigma^2}}\right)^n  \prod_{i=1}^n e^{ \frac{-1}{2} \cdot \frac{(x_i - \mu)^2}{\sigma^2}}$
or $\left(\frac{1}{\sqrt{2\pi}}\right)^n \left(\frac{1}{\sqrt{\sigma^2}} \right)^{n}\prod_{i=1}^n e^{ \frac{-1}{2} \cdot \frac{(x_i - \mu)^2}{\sigma^2}}$
or $\left(\frac{1}{\sqrt{2\pi}}\right)^n \left(\frac{1}{\sigma} \right)^{n}\prod_{i=1}^n e^{ \frac{-1}{2} \cdot \frac{(x_i - \mu)^2}{\sigma^2}}$
or $\left(\frac{1}{\sqrt{2\pi }}\right)^n\left(\frac{1}{\sigma^2} \right)^{n/2}\prod_{i=1}^n e^{ \frac{-1}{2} \cdot \frac{(x_i - \mu)^2}{\sigma^2}}$
as they are all equivalent,
and in any case multiplying the likelihood by a positive constant does not affect the maximum likelihood estimate
Answer: \begin{align}
\text{wrong: } & L(\sigma^2) = \prod_{i=1}^n \dfrac{1}{\sqrt{2\pi \sigma^2}} e^{-(x - \mu)^2/(2\sigma^2)} \\[10pt]
\text{right: } & L(\sigma^2) = \prod_{i=1}^n \dfrac{1}{\sqrt{2\pi \sigma^2}} e^{-(x_i - \mu)^2/(2\sigma^2)}
\end{align}
If nothing that changes as $i$ goes from $1$ to $n$ appears to the right of $\text{"}\prod_{i=1}^n \text{''},$ then what is that symbol there for? And $e^{-(x-\mu)/(2\sigma^2)}$ does not change as $i$ goes from $1$ to $n,$ then why not make it $\Big( e^{-(x-\mu)/(2\sigma^2)}\Big)^n\text{ ?} \phantom{\frac{\displaystyle\sum}{}}$
To address the $n/2:$
$$\frac 1 {\sqrt{\sigma^2}} = \left( \frac 1 {\sigma^2} \right)^{1/2}. $$


add watermark to all images uploaded in the site

Question: I am trying add watermark to all the images uploaded by users. Is there any preprocessor for the same? or any module to achieve it ?
Answer: Module ImageCache Actions is a well supported module that can add watermarks for Drupal 5,6,7.  It does this all by caching the image using imagecache.
Comment: I installed this module, but did not get how to configure the watermark part.
Comment: I don't remember completely,  but I"m pretty sure there is 2 setups.  #1. you create the imagecache with the watermark action (like you do for cropping, scaling, etc).   #2 for a node, you go to display fields and select from the dropdown how you want the image to be displayed.   If you are still having trouble let me know
Comment: will try and update u.
Comment: were you able to get it working?
Comment: no.. have to work on it little more


How do I programmatically update the order status?

Question: After Payment is accepted, I need to update the order status to "Completed" from the page controller.
How do I do this, on Drupal 8?
I find no documentation about this; there is an example for Drupal 7.
<code>// Updating Order status.
$orderObj = commerce_order_load($orderID);
commerce_order_status_update($orderObj, 'canceled', TRUE, 'Order Voided');
$orderObj->log = 'Order cancelled programatically';
commerce_order_save($orderObj);
</code>
Answer: You want to use the State Machine methods of the Commerce Order class.
It would be something like this, but it will depend on what you called your order states.
<code>$order_state = $orderObj->getState();
$order_state_transitions = $order_state->getTransitions();
$order_state->applyTransition($order_state_transitions['complete']);

$orderObj->save();
</code>
If you aren't sure, you can always check the <code>$order_state_transitions</code> array to see what options you have.
Comment: I think the state that needs to be set (default setup) is "placed"; also, i think you are missing a line where you need to assign the $order_state back to the Order before saving it.
Comment: No, you don't. Setting the state yourself would go against the pattern. You are welcome to post your own answer.
Comment: Yes, my idea was wrong. I posted a similar question (and answered it) here: https://drupal.stackexchange.com/questions/292291/how-do-i-programmatically-place-an-order
Answer: I think you are looking to "place" the order. You need to subscribe to the Event handler for this event: commerce_order.order.paid
and with this handler code:
<code>  public function paymentCompletedHandler($event) {
    $order = $event->getOrder();
    $order->getState()->applyTransitionById('place');
    return;
  }
</code>
Answer: This code did the job for me. You need to know the ID of the transition. In my case, it's 'cancel'
<code>$order = \Drupal\commerce_order\Entity\Order::load($order_id);
$order_state = $order->getState();
$order_state->applyTransitionById('cancel');
$order->save();
</code>
Answer: You can simply use set method.
<code>$order->set('state', 'completed');
$order->save();
</code>
Comment: this will bypass state transitions and break commerce_stock, potentially skip notifications, and other modules that hook into state transitions