Android SqLite Exception: unrecognized token in deleting from database

Question: I'm trying to delete everything from my database called Globals which contains a list of sessionID's. A SessionID is generated each time a user logs in and therefore previous sessionID's are not needed within the database and must be deleted since they will never be in use again. I implemented a method to delete all sessionID's within the database except for the  one specified but I get this error when I run my code:

"android.database.sqlite.SQLiteException: unrecognized token: "8a8878dc" (code 1): , while compiling"

How do I fix this?
This is my delete method for removing the sessionID's
public void deleteAll(String sessionID) {
    SQLiteDatabase db = this.getWritableDatabase();
    db.delete(TABLE_SESSIONSTATE, KEY_SESSIONID + " != " + sessionID , null);
}

and it is run in this code:
The result object  returns a string which gives the sessionID I want to use
SoapObject result = (SoapObject)envelope.bodyIn;
                if(result != null)
                {
                    globals = new Globals(getBaseContext());

                    String resultStr = result.getPropertyAsString(0);
                    resultStr = resultStr.replace("\n", "");
                    String [] resultArr = resultStr.split("\\^");
                    sessionID = resultArr[0];
                    globals.deleteAll(sessionID);
                }

Comment: `8a8878dc-7f5d-43c8-a88b-60a23831b9f3` is a string. Use it like a string `'8a8878dc-7f5d-43c8-a88b-60a23831b9f3'`
Answer: In SQL, strings must be written 'in quotes'.
However, to avoid formatting problems like this, you should use parameters:
db.delete(TABLE_SESSIONSTATE,
          KEY_SESSIONID + " != ?",
          new String[] { sessionID });

Comment: This appears to be deleting all from the database. I want to be able to keep only the one sessionID that is generated in the code from result
Comment: Is the session ID actually such a 36-character string?
Comment: yes, its coming from a WebService that autogenerates that sessionID. When a user logs in it generates a new sessionID
Answer: Try this:

Create Helper method that delete unwanted sessionID from the DB.
Create another Helper method that insert new SessionID
Call Method that deletes previous sessionID first follow by method that Insert new One.


Best boilerplate for Meteor project?

Question: Just started using meteor and built the first app using the to-do app tutorial.
Now I plan to use meteor for a project with bootstrap, is there a standard boilerplate available for this which gives me a file structure to work with ?
My app has a small to medium level of sophistication.
Comment: good one: https://github.com/themeteorchef/base
Answer: You could use Yeoman, a web scaffolding tool, to generate your Meteor projects.

Run npm install -g yo to install Yeoman.
Run npm install -g generator-meteor to install the Meteor generator.
Run mkdir new-meteor-project && cd $_ to create a new project directory.
Finally, run the Yeoman Meteor generator: yo meteor.

This generator is able to include Iron Router and Bootstrap:
$ yo meteor

     _-----_
    |       |    .--------------------------.
    |--(o)--|    |    Welcome to Yeoman,    |
   `---------´   |   ladies and gentlemen!  |
    ( _´U`_ )    '--------------------------'
    /___A___\
     |  ~  |
   __'.___.'__
 ´   `  |° ´ Y `

? Shall we include Iron Router? Yes
? Shall we include Bootstrap? Yes
   create client/client.js
   create client/lib/subscriptions.js
   create client/views/home.js
   create client/views/home.html
   create client/views/common/loading.html
   create lib/collections.js
   create public/robots.txt
   create server/publications.js
   create server/server.js
   create server/security.js
   create .meteor/.gitignore
   create .meteor/release
   create .gitignore
   create .jshintrc
   create .travis.yml
   create .editorconfig
   create LICENSE
   create README.md
   create client/routes.js
   create client/views/layout.html
   create client/styles/theme.css
   create .meteor/packages

If this generator does not meet your needs, you may want to search for another one.
Comment: Thank you, I will check this out, seems like yeoman is a massive collection of boilerplates. Also, I've started using Microscope with orionjs.

Best boilerplate for Meteor project?


Mediation analysis interpretation. negative path c but positive and significant paths for a and b

Question: Hello I have a problem interpreting the results of my mediation analysis (Baron and Kenny)
Path a between my IV (X) and M is positive and significant.
Path b between my Mediator and DP(Y) is also positive and significant.
Path c, the direct path between my IV(X) and DP(Y) is negative and significant.
Now when I add my mediator the relationship between X and Y becomes "more negative". it goes from -0.031 to -0.038 (significant value 0.000)
What does this say about the Mediator?
(I know there are other ways to analyze mediation but I want to wrap my head around this approach)
Thank you!!
Answer: This sounds like a suppressor effect. They are often pretty tricky to interpret.
Here's one example, that is similar to yours, except the direct effect switches from positive to negative: https://pubmed.ncbi.nlm.nih.gov/12595384/
This is in medical students, looking at conscientiousness. Basically, before medical school, conscientiousness positively predicts grades.
Towards the end of medical school, the direct effect of conscientiousness is positive, and the indirect effect goes negative.
Before medical school, conscientious students work harder. In medical school all students work as hard as possible. Conscientiousness helps earlier with grades, but that help needs to be removed at the end, because if you're not working as hard as you can, you're not in medical school any more.
Comment: As far as I read, also using this thread:https://stats.stackexchange.com/questions/73869/suppression-effect-in-regression-definition-and-visual-explanation-depiction  , a coefficient that is being strengthened is indicative of a suppressor effect. In my example the effect grows stronger in amplitude but in an absolute sense: -0.31> -0.38 which is what makes interpreting this case so difficult. Wouldn't it need to grow bigger e.g. from -0.31 to -0.2 in order to be a suppressor effect?
Comment: -0.31 to -0.38 is bigger.  Lower does not mean bigger. It is a bigger effect.
Answer: I agree with Jeremy that this is suppression, but I don't think they are complicated to interpret as they seem. Suppression in mediation occurs whenever you have two compensatory pathways, which occurs in any system that needs to maintain stability. If the focal predictor causes negative changes in the outcome, a stability-maintaining system would involve a compensatory pathway that increases the outcome in response to changes in the predictor.
Take for example the effect of exercise on weight. Exercising burns calories, which increases one's appetite and makes one eat more, and eating more causes weight gain. But as we know, exercising also causes weight loss through the burning of calories directly. There is a compensatory pathway: your body responds to increased burning of calories due to exercise by increasing your appetite to offset the changes in weight, thereby maintaining stability. To lose weight, the direct effect of burning calories on weight must be greater (in the negative direction) than the indirect effect through amount of food eaten, or you need to hold constant the amount of food eaten. This is why one needs to control their diet in addition to exercising if they want to lose weight; otherwise their increased appetite will maintain their current weight (or at least slow the weight loss).
Here, the situation is nearly identical to yours. Exercise (X) is positively related to food eaten (M) (A path), and food eaten is positively related to weight (Y) (B path). But exercise (X) has a direct negative effect on weight, holding constant food eaten (C' path). In total, exercise has a weak negative total effect on weight (C path), but holding constant food eaten, the direct effect of exercise on weight is pronounced.


Exact formula for $P_n(r)$, the probability of drawing a card of rank $r$ from a standard shuffled deck at the $n$-th draw without replacement.

Question: My question is rather easy to state, and perhaps easy to answer, but I'd need a pointer in the right direction. Suppose you have a standard 52-cards, well-shuffled deck, which contains $4$ cards for each rank (the rank of a card is the 'number' it displays, from $1$ to $13$). You draw one card at a time, for $n$ times. Cards already drawn are not put back into the deck, but just set aside. I would like to have a formula for the probability $P_n(r)$ that a card of rank exactly $r$ is drawn at the exact $n$-th extraction (i.e. after the first $n-1$ cards have been set aside).
Is anyone able to help me?
Comment: What have you tried?  Can you show your work?
Comment: Do you look at the $n-1$ drawn cards?  That is, do their values contribute to $P_n(r)$?
Comment: Am I missing something? Isn't the probability $1/13$ for any $n$ and any $r$? On the $n$-th card, which of the 13 ranks is more likely to be drawn than some other rank? Replacement or not, it's still $1/13$ unless you intend some conditional probability where you have info on the previous draws.
Answer: The probability of a $4$ on the $17$-th card is $1/13$, since each of the $13$ ranks is equally likely to be the rank chosen at that draw (since you are talking about absolute, not conditional, probability). And the answer is the same with or without replacement.
And similarly, of course, the probability of rank $r$ on draw $n$ is $1/13$, for the same reason.
Comment: Yes right, that's alot easier.
Comment: Ok, thank to you both.
Answer: We can split this problem into two steps: The first one is figuring out the probability that $x$ cards of rank $r$ are drawn in $n-1$ draws. The second step is to compute the probability that the $n$-th card is of rank $r$ given that $x$ cards of rank $r$ have already been drawn.
For the first step: The probability for drawing $x$ cards of rank $r$ using $n-1$ draws follows a hypergeometric distribution: https://en.wikipedia.org/wiki/Hypergeometric_distribution
For the second step: This is straight forward: Consider for example $x=2$. This means that $2$ cards of rank $r$ have already been drawn. Thus $2$ of the remaining $52-(n-1)$ cards are of rank $r$. Then the probability to draw a card of rank $r$ given that $2$ cards of rank $r$ have already been drawn is $\frac{2}{52-(n-1)}$.
Having figured out the solution to both steps you can use the theorem of total probability (in German "Totale Wahrscheinlichkeit", hope I did get the translation right) to combine the results and obtain your desired distribution.
Assume $n>4$: Then we obtain $P_n(k) = \Sigma_{i=0}^{4}p_X(i)\cdot\frac{4-i}{52-(n-1)}$ where $X \text{~ Hypergeometric}(4, 52, n-1) $. You can find the formula for the $p_x$ on Wikipedia using the link above. Use the parameters as I have given them: $K = 4, N = 52, n_{hypergeometric} = n-1$.
Comment: I included it in my post. Well to be honest it is not the full formula but the rest is really a matter of copying it from wikipedia.
Comment: $k$ denotes the rank of the card. But since for every rank the distribution behaves exactly the same, $k$ does not appear on the right-hand side. It does not matter whether you are looking at cards with a $5$ on it or whether you are looking at cards with a $6$ on it.
Comment: absolutely. It is dependent on $n$ though.
Comment: The probability of an Ace on the $11$-th draw is ..... $1/13$, because the probabilities, on the $11$-th draw, are the same for $A, 2, 3, 4, ..., 10, J, Q, K$. Which one of those ranks is more likely than another?


Union path connected disjoint subspaces, $A, B$ and $C$, $X=A\cup B\cup C$ is path connected

Question: Problem:
Let X be a topological space and let $A, B$ and $ C$ be path-connected subspaces of $X$. Show that if $A \cap B \neq \emptyset$ and $C \cap B \neq \emptyset$ then the union $A \cup B \cup C$ is path-connected.

My idea:
For a path connected space $P$, any points $p_1$ and $p_2$ can be connected to one another via a path $f: [0,1] \rightarrow P$ such that $f(0)=p_1$ and $f(1)=p_2$. So all $A, B, C$ have this property. Let their corresponding maps be:

$f_A: [0,1] \rightarrow A$ : $f(0)=a_1$ and $f(1)=a_2$, $f_B: [0,1] \rightarrow B$ : $f(0)=b_1$ and $f(1)=b_2$ and, finally, for $C$ $f: [0,1] \rightarrow C$ such that $f(0)=c_1$ and $f(1)=c_2$

So to prove the union of all these spaces, $X=A \cup B \cup C$, is path-connected, I was wondering if we could define a new map $f: [0,1] \rightarrow X$ such that $f(0)=x$ and $f(1)=y$ where $x$ and $y$ are any points in $X$ and the map $f$ is some composition of $f_A, f_B $ and $f_C$. But I have not managed to formulate this in any formal way.
Thanks for you help in advance
Answer: The idea is this one :
Take $p \in A \cap B$ and $ q\in B \cap C$
Let $x,y \in A \cup B \cup C$,

if $x\in A$ and $y \in A$, by path-connectedness of $A$, there exists a path between $x$ and $y$.
if $x\in A$ and $y \in B$, by path-connectedness of $A$, there exists a path between $x$ and $p$, and by path-connectedness of $B$, there exists a path between $p$ and $y$. So there exists a path between $x$ and $y$
if $x\in A$ and $y \in C$, by path-connectedness of $A$, there exists a path between $x$ and $p$, by path-connectedness of $B$, there exists a path between $p$ and $q$, and by path-connectedness of $B$, there exists a path between $q$ and $y$. So there exists a path between $x$ and $y$
etc.


Find entity id in database

Question: I am currently moving a website from Drupal. The information I need to transfer is divided to many DB tables and connected through entity_id (That is my understanding, I have no experience in Drupal).
E.g. I have 2 MySQL tables:
users — contains uids, passwords and emails
field_revision_field_user_profile_phone — contains phone numbers and entity_ids
I believe there should be a table that matches uids and entity_ids, that will let me build a MySQL query to join them, but I can't find it.
How do I join those tables?
Answer: In the database that contains entity_id (field_revision_field_user_profile_phone in this case) there is a column named entity_type. That would be a name of the table which contains both uid and entity_id.
Answer: For the second question how to join tables:
You can use Drupal db_select or db_query in querying the database and joining tables.
This will list all users name, mail, and password.
Example:
Using db_select
$query = db_select('users', 'u');
$query->join('field_revision_field_user_profile_phone', 'ei', 'ei.entity_id = u.uid');
$query->fields('ei', array('field_user_profile_phone_value'));
$query->fields('u', array('name', 'mail', 'pass'));

$results = $query->execute()->fetchAll();
foreach($results as $result) {
  // ...
}

Using db_query
SELECT ei.field_user_profile_phone_value AS field_account_employee_id_value,
       u.name AS name,
       u.mail AS mail,
       u.pass AS pass
FROM users u
INNER JOIN field_revision_field_user_profile_phone ei ON ei.entity_id = u.uid

Additional Resources:
Documentation of db_select function.
Documentation of db_query function

Find entity id in database


Breakdown interactions in MIXED model SPSS

Question: I have a 2x2x2 design, where two of the variables are repeated measures and one is a between-subjects manipulation. I need to break down the interaction to look at the 2x2 mixed interactions (Repeated Var1 x Bwn-subjects var) at each level of Repeated Var2. How do I do this using a MIXED MODEL in SPSS (Not through ANOVA or GLM)?
Answer: The TEST subcommand on the MIXED command is the way to go about this. It applies to fixed effects within the mixed model fitted in MIXED, and works similarly to the LMATRIX subcommand in GLM and UNIANOVA.
Using TEST or LMATRIX in general designs requires some understanding of estimable functions, which isn't exactly trivial. For a situation like this, there's a little trick I can recommend that makes things a bit easier.
Once you've fitted your model and found that you've got a three-way interaction, you can re-fit the same model with a simpler parameterization that results in one fixed parameter per cell, with no redundant or linearly dependent parameters as are usually involved in the overparameterized version of the model used by default in MIXED (and GLM/UNIANOVA). This makes it really simple to specify a TEST (or LMATRIX) subcommand that involves just one coefficient per cell in the fixed-effects design, so it's easy to get the comparisons you want.
So for a model like this, instead of specifying the factorial design on the FIXED subcommand or in the Fixed dialog, you suppress the fixed intercept and specify only the three-way interaction term. Compare the overall results for the model fit to the original fitting of the model and you'll see that everything matches up. Also, you can compare the fixed-effects parameter estimates from this modified parameterization to the EMMEANS for the three-way interaction in the original fitting to see that they match up and have the same standard errors.
This lays out the design so that you can specify any linear combination of the individual cell means quite easily. For getting simple interaction effects for a two-way interaction within each level of the third factor, you'd need something like a 1 -1 -1 1 pattern for the four cells that make up the two-way interaction of interest within each level of the third factor.
Suppose the three factors are named Rep_Var1, Rep_Var2, and Bet_Var. If you specify the FIXED subcommand as:
/FIXED Rep_Var1*Bet_Var*Rep_Var2
you can specify
/TEST ALL 1 -1 -1 1 0 0 0 0
/TEST ALL 0 0 0 0 1 -1 -1 1
to get interaction contrasts nested within each level of Rep_Var1. You can specify as many TEST subcommands as you want.


como pegar nome da classe com javascript

Question: Estou fazendo um accordion e já está funcional como eu gostaria (só falta alguns detalhes que irei acertar depois). Só que agora eu preciso que ao ser clicado e o painel expandido, o sinal de + (mostrar mais) seja alterado para - (mostrar menos).
P.S.: Sou iniciante em Javascript, porém a lógica e pegar o nome da classe (ou tentar pegar) e retornar um boolean, se verdadeiro executar tal ação, que é alterar o texto de um determinado elemento.
O que eu tenho:

  var acc = document.getElementsByClassName("accordion");
  var i;

  for (i = 0; i < acc.length; i++) {
    acc[i].addEventListener("click", function() {
        this.classList.toggle("active");
        var panel = this.nextElementSibling;
        if (panel.style.display === "block") {
        panel.style.display = "none";
        } else {
        panel.style.display = "block";
        }
    });
  }
.accordion {
  background-color: #0c4b7a;
  color: white;
  cursor: pointer;
  padding: 18px;
  width: 100%;
  border: none;
  text-align: left;
  outline: none;
  font-size: 15px;
  transition: 0.4s;
}

.active, .accordion:hover {
  background-color: #ccc;
}

.panel {
  padding: 0 18px;
  display: none;
  background-color: white;
  overflow: hidden;
}

.panel p:hover {
  background-color: #F47920;
  color: white;
}

Accordion

<button class="accordion">Título 1 +</button>

t is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout.

There are many variations of passages of Lorem Ipsum available

<button class="accordion">Título 2+</button>

Lorem Ipsum is simply dummy text of the printing and typesetting industry.

O código a seguir seta o nome da classe no elemento:

document.getElementById("myDIV").className = "mystyle";

Eu queria fazer tipo um get e salvar em uma variável e verificar se é true, se for realizar a lógica citada mais acima.
Comment: Neste caso: `document.getElementsByClassName("output").value()`, se quiser fazer isso com JQuery, fica até mais simples.... `$("output).val()`
Comment: Olha, o `document.getElementById()` deixa claro, "Documento.PegarElementoPeloID()"... Neste caso, você deve utilizar o `document.getElementsByClassName()` para poder pegar a classe do que você quer... Exempĺo: "`document.getElementsByClassName("output")`"
Comment: Sim, porém eu irei pegar o elemento pela classe e todos os seus filhos, correto? Se tiver como pegar a classe e realizar um filtro para pegar somente o nome dela ou montar um array para enfim verificar qual possui a classe *active* ai tudo bem.
Comment: valeu, mas eu estou fazendo isso para aprender javascript vanilla, pois estou querendo aprender Reactjs depois.
Answer: Para isso basta você pegar o item do acordeão que foi clicado utilizando o primeiro parâmetro da função que você declara no click.
Feito isso, você consegue acessar o currentTarget do evento, que te retorna o elemento cujo o click está atrelado e pode pegar o span utilizando o querySelector para, então, alterar o textContent, conforme exemplo a seguir:

var acc = document.getElementsByClassName("accordion");
  var i;

  for (i = 0; i < acc.length; i++) {
    acc[i].addEventListener("click", function(e) {
        let elem = e.currentTarget.querySelector('span');
        elem.textContent = elem.textContent === '+' ? '-':'+';
        this.classList.toggle("active");
        var panel = this.nextElementSibling;
        if (panel.style.display === "block") {
        panel.style.display = "none";
        } else {
        panel.style.display = "block";
        }
    });
  }
.accordion {
  background-color: #0c4b7a;
  color: white;
  cursor: pointer;
  padding: 18px;
  width: 100%;
  border: none;
  text-align: left;
  outline: none;
  font-size: 15px;
  transition: 0.4s;
}

.active, .accordion:hover {
  background-color: #ccc;
}

.panel {
  padding: 0 18px;
  display: none;
  background-color: white;
  overflow: hidden;
}

.panel p:hover {
  background-color: #F47920;
  color: white;
}

Accordion

<button class="accordion">Título 1 +</button>

t is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout.

There are many variations of passages of Lorem Ipsum available

<button class="accordion">Título 2+</button>

Lorem Ipsum is simply dummy text of the printing and typesetting industry.

Outra possibilidade, sem utilizar o evento recebido é fazer da seguinte forma:

var acc = document.getElementsByClassName("accordion");
  var i;

  for (i = 0; i < acc.length; i++) {
    acc[i].addEventListener("click", function() {
        this.classList.toggle("active");
        this.querySelector('span').textContent = this.classList.contains('active') ? '-' : '+';
        var panel = this.nextElementSibling;
        if (panel.style.display === "block") {
        panel.style.display = "none";
        } else {
        panel.style.display = "block";
        }
    });
  }
.accordion {
  background-color: #0c4b7a;
  color: white;
  cursor: pointer;
  padding: 18px;
  width: 100%;
  border: none;
  text-align: left;
  outline: none;
  font-size: 15px;
  transition: 0.4s;
}

.active, .accordion:hover {
  background-color: #ccc;
}

.panel {
  padding: 0 18px;
  display: none;
  background-color: white;
  overflow: hidden;
}

.panel p:hover {
  background-color: #F47920;
  color: white;
}

Accordion

<button class="accordion">Título 1 +</button>

t is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout.

There are many variations of passages of Lorem Ipsum available

<button class="accordion">Título 2+</button>

Lorem Ipsum is simply dummy text of the printing and typesetting industry.

Dessa forma, você pode usar direto o this para pegar o span do + e alterar para menos verificando se o classList dele contem a classe active.
Comment: Ambas funciona, mas achei a segunda maneira melhor por utilizar a referência da própria classe. Valeuuu!
Answer: Pegar o nome da classe se for um input ou select:

var elementos = document.getElementsByClassName("nome da classe").value;

Pegar o conteúdo de um elemento se não for input ou select:

var elementos = document.getElementsByClassName("nome da classe").innerHTML;

Verificar se um elemento é boleano

if (typeof elementos === "boolean") {
  //Faz aqui sua condição caso a sua variável de teste for booleana
}

OBS: Não entendi direito se é isso que você quer. Pareceu ser pegar o valor de um elemto e verificar se ele é boleano.


Weak form for Linear Dynamic Wave Equation of Dirichlet/Neumann's boundaries?

Question: I have a linear problem with double derivate of space and time, which has Dirichlet boundary condition in $(1)_{2}$ and Neumann's boundary condition in $(1)_{3}$:
\begin{equation}
\frac{\delta^{2} u}{\delta t^{2}} - c^{2} \Delta u = f \text{ in } \Omega
\end{equation}
\begin{equation}
u = 0 \text{ on } \delta \Omega \text{ or}
\end{equation}
\begin{equation}
\nabla u \cdot n = 0 \text{ on } \delta \Omega
\end{equation}
with conditions
\begin{equation}
u(0,x) = u_{0}(x) \text{ in } \Omega
\end{equation}
\begin{equation}
\frac{\delta u}{\delta t}(0, x) = v_{0} (x) \text{ in } \Omega.
\end{equation}
Which is the weak form of the problem?
My attempt:
\begin{equation}
\int (\frac{\delta^{2} u} {\delta t^{2}} - c^{2} \Delta u) \cdot v dx = \int fv \cdot dx,
\end{equation}
for $\forall v \in V_{n}.$
Handling two different parts separately
\begin{equation}
\int_{\Omega} \frac{\delta^{2} u} {\delta t^{2}}v dV
+ c^{2} \Big[ \int_{\Omega} \nabla u \cdot \nabla v dV
- \int_{\delta \Omega} \nabla u \cdot \hat{n} \cdot v dA \Big]
=
\int fv \cdot dx.
\end{equation}
Comment: Sorry, I'm not sure what tags fit your question best. I do know that finite fields don't fit (they have nothing to do with real numbers nor vector fields - they are a concept from abstract algebra). I replaced it with the tag *boundary-value-problem* wishing that it would attract people who can actually help you.
Comment: @JyrkiLahtonen Thank you Jyrky! I completely agree with you. Your tag is good!
Answer: I finally got the result which should be right one.
By integrating and multiplying Equation (1) with $v$
\begin{equation}
\int v \ddot{u} dx + c^{2} v \Delta u = \int fv dx
\end{equation}
using Green I we get
\begin{equation}
\int v \ddot{u} dx
- \int_{\partial} c^{2} v \frac{\partial u}{\partial n} dS + \int \nabla c^{2} v \cdot \nabla u dx
= \int fv dx.
\end{equation}
So the weak form is
\begin{equation}
(v,\ddot{u}) + c^{2}(\nabla v, \nabla u)
- c^{2} (v, \frac{\partial u}{\partial n})_{\partial \Omega} = (f,v).
\end{equation}


how to display http_post in php?

Question: I've got this http_post xml sending in my android project:
try {
            xml_input();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Log.e("Hiba!", "Xml_input fgv hivasa");
        }

        // TODO Auto-generated method stub
        HttpPost httppost = new HttpPost("http://users.atw.hu/festivale/xml_post.php");
        StringEntity se;
        try {
            se = new StringEntity(globalconstants.xml_out, HTTP.UTF_8);
            se.setContentType("text/xml");
            httppost.setHeader("Content-Type",
                    "application/soap+xml;charset=UTF-8");
            httppost.setEntity(se);

            HttpClient httpclient = new DefaultHttpClient();
            BasicHttpResponse httpResponse = (BasicHttpResponse) httpclient
                    .execute(httppost);

            HttpEntity r_entity = httpResponse.getEntity();
            String xmlString = EntityUtils.toString(r_entity);

            System.err.println("Error...." + xmlString);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

How can i display this in on my php site?
And is this a good xml sending if i want some rules etc. sending to a server?
Comment: what exactly do you want to display?
Comment: possible duplicate of [Php reading xml in post request](http://stackoverflow.com/questions/2068875/php-reading-xml-in-post-request)
Comment: just pass your xml String in a POST Parameter , and then display it in PHP via : `$xml = $_POST['yourParameterXML']; echo $xml;`
Comment: that's what i don't understand what is the my parameter? because i do not send any parameters not like this:List params = new ArrayList();
Answer: You can access http_post data using $_POST superglobal associative array in php. Like-
echo $_POST['foo'];

Comment: i understand that... but how do i send this 'foo' with this code?because no such line as: List params = new ArrayList();
Comment: @david Try to set content-type header to "application/x-www-form-urlencoded". And send plain text to see if the data is even sent or not.
Comment: but how can i display this on the php site? because now i do not send any parameters as you said like 'foo'...
Comment: @david have you tried `print_r($_POST)`?

how to display http_post in php?


2D array index positions "touching"

Question: I'm looking to find a way to be able to return if positions in a 2d array are both "touching" and similar values, tracing all the way around. Before I get into this there is a very similar question asked, and solved here, but it's written in python which I know nothing of. To further expand:
f f f f

f T T f

f T T f

f f f f

starting at [0][0] it would return all the falses in that array because they are the same value and chain back to [0][0].
f f f T f f f

f T f T f T f

f f f T f f f

but based on this one, starting at [0][0] would only return [0][0,1,2] , [1][0,2] , and [2][0,1,2]. however if you were to start at [0][4], it would return all the falses after [n][3] because they are the same value as the start, and touching.
Not looking for anyone to help me write code exactly but maybe point me in the right direction. Please excuse my novice level in advance, and thank you very much!
Comment: It's not clear what kind of problem you have. Error? Wrong values returned? Also you have an error with description - `[0][0,1,2]` is mentioned twice
Comment: apologies I was attempting to simplify the writing. that translates to [0][0], [0][1], [0][2]. I was looking for a type of algorithm that handles this or a point in that direction. Dmitry helped me below with a "breadth first search" alg. Thanks!
Comment: This is known as the [Flood fill](https://en.wikipedia.org/wiki/Flood_fill) algorithm.
Answer: It seems that you have a graph problem and you are looking for Breadth First Search or alike algorithm where

Graph nodes: all valid (f) array items
Graph edges: if and only if array items are neighbors

Implementation:
private static IEnumerable<Tuple<int, int>> Touching(char[,] items,
                                                     Tuple<int, int> startAt,
                                                     char letter = 'f') {
  if (startAt.Item1 < 0 || startAt.Item1 >= items.GetLength(0) ||
      startAt.Item2 < 0 || startAt.Item2 >= items.GetLength(1))
    yield break; // or throw ArgumentOutOfRangeException
  else if (items[startAt.Item1, startAt.Item2] != letter)
    yield break;

  Queue<Tuple<int, int>> agenda = new Queue<Tuple<int, int>>();
  HashSet<Tuple<int, int>> visited = new HashSet<Tuple<int, int>>() { startAt };

  agenda.Enqueue(startAt);

  while (agenda.Any()) {
    for (int i = agenda.Count - 1; i >= 0; --i) {
      var point = agenda.Dequeue();

      yield return point;

      // Manhattan: left, right, top, bottom neighbors only, no diagonal ones
      var validNeighbors = new Tuple<int, int>[] {
         new Tuple<int, int>(point.Item1 - 1, point.Item2),     // left
         new Tuple<int, int>(point.Item1 + 1, point.Item2),     // right
         new Tuple<int, int>(point.Item1, point.Item2 - 1),     // top
         new Tuple<int, int>(point.Item1, point.Item2 + 1),}    // bottom
      .Where(p => p.Item1 >= 0 && p.Item1 < items.GetLength(0)) // Within array
      .Where(p => p.Item2 >= 0 && p.Item2 < items.GetLength(1)) // Within array
      .Where(p => items[p.Item1, p.Item2] == letter)            // valid point
      .Where(p => visited.Add(p));                              // not visited

      foreach (var p in validNeighbors)
        agenda.Enqueue(p);
    }
  }
}

Test:
 char[,] data = new char[,] {
    { 'f', 'f', 'f', 'T', 'f', 'f', 'f',},
    { 'f', 'f', 'f', 'T', 'f', 'f', 'f',},
    { 'f', 'f', 'f', 'T', 'f', 'f', 'f',},
  };

  string report = string.Join(Environment.NewLine,
    Touching(data, new Tuple<int, int>(0, 0), 'f'));

  Console.WriteLine(report);

Outcome (all these items below are touching i.e. reachable from the startAt point - (0, 0)):
(0, 0)
(1, 0)
(0, 1)
(2, 0)
(1, 1)
(0, 2)
(2, 1)
(1, 2)
(2, 2)

With a help of Linq you can organize the report in different way (like in the question):
var report = string.Join(Environment.NewLine,
  Touching(data, new Tuple<int, int>(0, 0), 'f')
    .GroupBy(item => item.Item1, item => item.Item2)
    .OrderBy(chunk => chunk.Key)
    .Select(chunk => $"[{chunk.Key}][{string.Join(", ", chunk.OrderBy(x => x))}]"));

And have the response below:
[0][0, 1, 2]
[1][0, 1, 2]
[2][0, 1, 2]

Comment: Thank you so, so much. This is absolutely perfect and very informative.

2D array index positions "touching"


Error Code 1111. Invalid use of group function

Question: So this works:
SELECT c.name AS country_name, c.population AS country_population, SUM(ci.population) AS city_population, ROUND(100*(SUM(ci.population)/c.population)) AS city_population_percent
FROM country AS c
JOIN city AS ci
ON c.code = ci.countrycode
WHERE c.continent = 'Europe'
GROUP BY c.name

But I need to only grab the city_population_percent values greater than 30, so I try this:
SELECT c.name AS country_name, c.population AS country_population, SUM(ci.population) AS city_population, ROUND(100*(SUM(ci.population)/c.population)) AS city_population_percent
FROM country AS c
JOIN city AS ci
ON c.code = ci.countrycode
WHERE c.continent = 'Europe'
**AND ROUND(100*(SUM(ci.population)/c.population)) > 30**
GROUP BY c.name

And that's when I get:

Error Code 1111. Invalid use of group function

That is, it fails when I add this condition in the WHERE:
AND ROUND(100*(SUM(ci.population)/c.population)) > 30

Comment: In addition to using the `having` clause: your general usage of `group by` is invalid in (standard) SQL. MySQL's sloppy implementation of the `group by` allows something that would fail in any other DBMS. For more details please read this: http://www.mysqlperformanceblog.com/2006/09/06/wrong-group-by-makes-your-queries-fragile/ and this: http://rpbouman.blogspot.de/2007/05/debunking-group-by-myths.html
Answer: So you have to move this condition to the HAVING clause
SELECT c.name AS country_name, c.population AS country_population, SUM(ci.population) AS city_population, ROUND(100*(SUM(ci.population)/c.population)) AS city_population_percent
            FROM country AS c
            JOIN city AS ci
            ON c.code = ci.countrycode
WHERE c.continent = 'Europe'
GROUP BY c.name
HAVING ROUND(100*(SUM(ci.population)/c.population)) > 30

Comment: Don't forget that this invalid use of `group by` will just return random data that might no be the correct result.
Answer: You're using aggregate functions in a where clause, something you cannot do in SQL.
Use the HAVING clause instead:
WHERE c.continent = 'Europe'
GROUP BY c.name
HAVING ROUND(100*(SUM(ci.population)/c.population)) > 30


Leading tone and resolving tension

Question: Is it always a third that "leads" to the root? For example, if we have GBD, it's B that leads to the C. Could it be also BDF that leads to C, or EGB? All of them contain B, a tone that leads to C. Do all of them lead to C? Can all of these B act as the leading tones or only the one in third (GBD)?
Second thing is about the half step thing. Can we resolve a half step lower, isntead of resolving by going higher? What I mean is can we resolve to Bb (going down) instead of C (going up) when we have B as a leading tone (again with GBD chord, for example)?
Answer: You have more than one question wrapped up in your post.
First, the fact that other chords (in the key of C) have the B in them doesn't mean you will create the feeling of tension and relief when moving from one to the other.  You example of EBG (the minor chord on the iii of the key) does not really create this feeling, there is movement but not "strong" movement.  The GBD chord is the V (five) of the key and has a special relation to the CEG (the one) chord.  The movement of GBD to CEG involves several intervals and it's the relation of all of them that creates a resolution.  In classical theory books they would state that the "V has a natural tendency to want to move to the I".  This doesn't mean that other movement is not acceptable, but none have that strong or natural tendency.  As Tim points out there is the V7 chord, in the key of C this is GBDF.  The movement of V7 --> I has 2 half step movements B-->C and F-->E which further strengthens the feeling of tension and resolution.
In your example of EGB --> CEG, iii --> I, the iii chord is a natural extension of the I as it creates the major seventh chord, CEGB.  In fact, in Jazz the iii chord is sometimes used to substitute the I, which creates no real feel of movement other than changing inversion.  Part of what creates the tension and release in the V-->I is the specific inversions used.  We typically try to create close movement from one chord to the other.  The fact is that not all V-->I movements have the same degree of tension-release, or resolution.  So, you can create more (or less) resolution based on your choice of specific note movement from one chord to the other.
In response to your idea of moving backwards from C to B, yes you absolutely can create resolution that way but it may not work as well as B-->C in the key of C.  If you are in C, the natural B chord is a diminished.  Moving to a diminished chord from a major chord would create tension rather than remove tension.  But in a string of chords one could keep moving from B(dim) to E7 to A(min) and there would eventually be resolution to the A(min).
The V chord is really what makes the resolution (in the classical sense) work.  Along these lines Jazz musicians will frequently "fill in" progressions by adding the V7 chord before each chord of an existing progression, treating the original chords as temporary I chords.  The device is really V7-->I rather than move a half step.
As a final comment to your question about moving using other half steps, there are only 2 half steps in the Major scale so your only options are 7-->8 and 4-->3.  This is present in the V7-->I chord change.  If you want to stay "in key" you don't have other options but you can always use chromatic notes to create more tension.  A common progression is I--> I#(dim)-->ii-->ii#(dim)-->iii-->IV or some variant of this.  It creates a slow, smooth, chromatic walk up from the I to the IV that contains some feel of resolution in it.
So, you can do what you want in a creative sense but there is a tested method to making this work.
Answer: The third (essentially major third) of V is called the leading note/tone for that very reason. It leads. more often than not, and sounds like it should, if It doesn't (!) to the root note of I.
Often the 'tension/release' involves movement of a semitone - the smallest step in Western music. In the V(7)>I, named the perfect cadence, there's another semitone step. That's between the 7th of the V chord - in key C, the note F - which resolves nicely downwards to the defining third of C, the I chord.
There's also another downward resolution which involves the Vb9 chord, G b9 here. Note - not Gb9, aka F#9, a completely different chord. Sometimes it's written G7b9 to avoid ambiguity. The b9 part of G7 is Ab, which again has a semitone to move to the G note (5 of root C).
There's another interesting cadence tritone  substitution, which involves a move from Db7 to C. Db7 is made up from Db, F, Ab and B, and you'll notice an F and a B in there. The two pivot notes which in key C are involved in G7! That chord also uses the leading note to get back to tonic, root I.
Answer: Considering C major as the key, notes G B D represent chord G, which functions as the dominant V chord. As a dominant, tension is high and tends to go to a tonic function chord like C. Notes B D F is chord Bdim, that functions as the VII grade which also happens to be dominant. B is half-step from the tonic C, this might be the reason why these 2 chords tends to go back to C and release tension.
However, there is another chord that also has B, that is Em (E G B) which is grade III and works as mediant. The reason for not being classified as dominant might be because it shares 2 of the 3 notes with the tonic C chord (E and G). This is an example where a regular chord with B might not create much tension.
Answer: As there's been no response to a couple of perfectly good answers, shall I try saying much the same thing in a different way?
Within the context of C major tonality, B is the leading note, with a tendency towards resolving on C.  This tendency is reinforced by including it in a G major chord - G, the dominant note - also has a tendency towards C - the tonic.  If we add an F - a tritone interval from B - forming a G7 chord, the tendency becomes even stronger as the F tends towards E, part of the tonic chord.
But yes, the B can go to other places.  Music is full of both expected movements - 'resolutions' - and unexpected ones.  Many of the unexpected ones will involve a move away from C major.  For instance, G7 (B melody) could resolve to A major (C# melody).
Or we could take advantage of the symmetrical nature of the tritone to harmonise F-B not as part of a G7 chord but as part of Db7 (better call the B a Cb though!).   F will become the leading note of Gb major.

Leading tone and resolving tension


Java:output Strange in printstream

Question: why output so strange 0022 =18?
hello everyone to day i have test.the question is "what is the output of
System.out.println(0022);

i so confuse why Answer is 18
explain needed
Answer: If the first digit of an int literal is 0, Java interprets the number in octal (base 8).

Java:output Strange in printstream


Dirichlet problem with odd function.

Question: Let $\Omega \subset \mathbb{R}^2$ be open, bounded and symmetric with respect to the origin. Let$ f:\partial \Omega \to \mathbb{R} $ be odd and continuous function. Show that if $u$ is solution of:
$$
\begin{cases}
\Delta u(x)&=0,&\text{ if }x \in \Omega \\
\phantom{-}u(x)&=f(x),&\text{ if }x \in \partial\Omega
\end{cases}
$$
then $u$ is odd.
Hint: study of the Laplacian's invariance in relation to $T(x,y)=(-x,-y)$
I tried to show that $\Delta u= \Delta (u\circ T)=0$, but how to finish?
Answer: If you show that $\Delta (u\circ T)=0$ in $\Omega$ you're done by uniqueness.
Indeed, first note that since $\Omega$ is bounded and symmetric with respect to the origin then $(x,y)\in\partial\Omega$ iff $(-x,-y)\in\partial\Omega$. Then, using that $f$ is odd and $u$ a solution we have for all $(x,y)\in\partial\Omega$
$$u(x,y)=f(x,y)=-f(-x,-y)=-u(-x,-y)=-(u\circ T)(x,y).$$
Now, as you noted $\Delta(u\circ T)=0$, which follows by symmetry of $\Omega$ and the identities for all $(x,y)\in\Omega$ $$\partial^2_x(u\circ T)(x,y)=\partial^2_xu(-x,-y),\\\partial^2_y(u\circ T)(x,y)=\partial^2_yu(-x,-y).$$
Finally, this implies that both $u$ and $-(u\circ T)$ are solutions to your Dirichelt problem. The fact the $f$ is continuous implies that you only have one solution, hence $$u(x,y)=-(u\circ T)(x,y)=-u(-x,-y)$$ for all $(x,y)\in\mathbb{R}^2$.
Note: While I was writing this, another answer was posted. The solution is essentially the same: maxima principle $\Rightarrow$ uniqueness.
Comment: I lost a bit in the derivatives. $\frac{\partial u}{\partial x}(-x,-y)=-\frac{\partial u}{\partial x}(x,y)$, Right?
Comment: The chain rule reads $\partial_x(u\circ T)(x,y)=\partial_xu(T(x,y))\partial_xT(x,y)=-\partial_xu(-x,-y)$.
Answer: If you already showed that      $\Delta u(-x, - y) =0$, take $v=u(x, y) +u(-x, - y) $.
By the fact that f is odd, $v$ is solution for the problem:
\begin{equation}
\begin{cases}
\Delta v=0 \\
v=0, \ \ \ in \  \partial \Omega
\end{cases}\end{equation}
So, by the maxima principle $v=0$ in $\Omega $ then $u(x, y)=-u(-x, - y) $ in $\Omega$.

Dirichlet problem with odd function.


Does it makes sense to perturb images on-the-run while training CNNs?

Question: I'm training a convolutional neural network by adding small perturbations (like rotation and shifting) to the images each time it gets a batch data.
I think a better way of doing this could be to generate a bigger data set by oversampling with these transformations before training, however I don't have much RAM to store a bigger data set, so I decided to transform them on the run. But it means that now I'm supplying a different data set in each epoch.
I think it should make sense, and the training, in fact, converges to a better performance, but it watches a zig-zaggy road, which is understandable I guess. So am I safe to assume that I'm not making a mistake? Also is there a better way for this, i.e. training a generalizable classifier under a small data set and limited computational resources?
Thanks for any help !
Comment: I don't see anything wrong with doing that, it's actually a nice solution to a hardware constraint problem. Dropout, a very popular regularization technique for deep nets, also introduces noise during each forward pass, so in my opinion there is nothing wrong with these sorts of techniques. Nicely done!
Answer: Yes, it does make sense and actually this is what is done in practice.
Why does it makes sense?
Random permutations might change the statistics of the dataset. By performing a new random permutation in each epoch, these effects tend to cancel out.
Imagine performing a random rotation on an image with a range of $[-5\%, +5\%]$. By storing the rotated image, you are feeding the same image to the network during each epoch. By transforming the image anew during each epoch, a different image is fed to the network.
This both increases the effective size of your augmented dataset and reduces the bias caused by the augmentation (because you don't perform the same perturbation each time).
Note on the memory issues:
When dealing with images, it is preferable to not load the whole dataset in your memory during training; in most cases datasets are too large to fit into your memory. I'd recommend using a generator to load image batches one at a time. This way you don't have to concern yourself on how large the dataset is.


How can I split up a block of text using substr and a read more link to show the rest of it?

Question: In wordpress a simple call is used to show the page content:
the_content()

I'm trying to develop a mobile optimised version of this, that will only show a portion of the content, with a 'Read More' link at the end, which would 'slide down' the rest of the content for the user to read.
So far, I've only been able to come up with this:
$content = get_the_content();
echo substr($content, 0, 200)." Read more";

However, I'm not sure how I can get to show the rest of the content, even at all let alone sliding down.
Is there a way I can switch from substr to the full the_content() when the link is clicked?
Answer: You're going to need to loop through the fullc ontent dividing it into blocks.
Then you will need to display the first block.
The button should allow you to display the next block with a simple counter keeping track of the next block
CSS
.hidden
{
   display: none;
 }

PHP
$content = get_the_content();
///You're going to need some additional checks here for the ending sequence
for($I = 0; $I < str_len($content) / 200; $I++)
{
    echo "
" . substr($I * 200, ($I + 1) * 200) . "
";
}
echo "Read More";

JS
 var I = 0;
 DisplayNext();
 function DisplayNext()
 {
 ///You should check to make sure the element exists and handle when you ge tto the last element.
 document.getElementById("Content" + I++).style.display = "block";
 }

Comment: I'm getting a call to undefined function len() - is that even a function?
Comment: Do you mean strlen() ?
Comment: Hmm I'm not sure what's going on here, as none of the content is showing up when the page loads, although the read more link does.. but doesn't do anything when clicked.
Comment: Should be onclick="DisplayNext();"  And you can add DisplayNext(); in the JS to load the first block...
Comment: I don't know, nothing's showing up with the content, all i get is a read more link that goes nowhere. No JS errors or warnings or anything.
Comment: IS your content length less than 200? As I commented you're going to want to handle the end condition properly, right now it'll just cut off to the last full 200 characters.  (PHP For loop)
Comment: It's definitely not less than 200, there's about 3 or 4 paragraphs on the page i'm testing. I'm leaving it for now, coming back to it Monday. Thanks for your help


Atualizar data a cada update em uma tabela

Question: Possuo uma tabela pessoa. Nela eu tenho um campo chamado pe_modified que tem como objetivo ter a data da última modificação na tabela.
Ao invés de eu ter de atualizar na consulta, é possível ser automático ?
Existe algum tipo de campo ou um valor default que atualiza a hora sempre que é realizado um update na tabela?
Comment: Já viu falar em triggers? Veja: https://www.postgresql.org/docs/9.2/static/plpgsql-trigger.html
Answer: A função now() retorna a data atual. Uma maneira de automatizar esse mecanismo é utilizando uma trigger como a do código abaixo:
CREATE OR REPLACE FUNCTION update_pe_modified_column()
RETURNS TRIGGER AS $$
BEGIN
   NEW.pe_modified = now();
   RETURN NEW;
END;
$$ language 'plpgsql';

CREATE TRIGGER update_pessoa_pe_modified
BEFORE UPDATE ON pessoa
FOR EACH ROW EXECUTE PROCEDURE
update_pe_modified_column();

Fonte: Automatically updating a timestamp column in PostgreSQL
Answer: Boa tarde.
Para atualizar campos antes ou depois de eventos, é necessário criar uma trigger.
Abaixo um exemplo de trigger:
CREATE OR REPLACE FUNCTION trg_update_conhecimento()
RETURNS trigger AS
$BODY$
BEGIN
    INSERT INTO conta_corrente
    (descricao, data, fg_debito, valor, numero)
    VALUES
    ('CONHECIMENTO GERADO', CURRENT_DATE, true, NEW.frete_peso + NEW.frete_km, NEW.numero);

    RETURN NEW;
END
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;

CREATE TRIGGER trigger_update_conhecimento
  AFTER UPDATE
  ON conhecimento
  FOR EACH ROW
  EXECUTE PROCEDURE trg_update_conhecimento();

A trigger acima faz um insert na tabela conta_corrente após a execução de um update na tabela conhecimento.
Comment: Creio que esta resposta seria mais útil se você desse um exemplo referente as tabelas/colunas citadas pelo @Jonathan.


ReflectionException in Route.php line 281: Function () does not exist

Question: In Laravel 5 i'm Facing This Problem..
Here Is My Code
Route::group(['middleware' => ['web']], function(){

Route::get('/login', ['as' => 'login', 'user' => 'AuthController@login']);
Route::get('/handlelogin', ['as' => 'handlelogin', 'user' => 'AuthController@handlelogin']);
});

Comment: If you're using 5.2.27 and higher, remove web middleware.
Comment: FatalErrorException in ae8df401b51f2e82f0ff768d0c8b5c0050695036.php line 17:
syntax error, unexpected ':', expecting ',' or ';'
Comment: That's a syntax error now inside one of your views.
Comment: Btw, chek inside `storage/framework/views/ae8df401b51f2e82f0ff768d0c8b5c0050695036.php` to see in which line of your view you have the error.
Comment: it is uses not user, it uses the controller and method.
Answer: You have 'user' => 'AuthController@login and 'user'=> 'AuthController@handlelogin'
It should be 'uses' =>
Route::group(['middleware' => ['web']], function(){

    Route::get('/login', ['as' => 'login', 'uses' => 'AuthController@login']);
    Route::get('/handlelogin', ['as' => 'handlelogin', 'uses' => 'AuthController@handlelogin']);
    });


Solving the initial value problem which is given as follows

Question: $$z'=z(z-5)(z-20)$$ where $z(3)=10.$
$\lim_{x\rightarrow \infty} z(x)=? $
My attempt:
$$\frac{dz}{z(z-5)(z-20)}=dx$$ taking integral and using the initial condition, I found
$\frac{z^3(z-20)}{(z-5)^4}=-16e^{300x-900}$.
(it may be wrong)
And then ?
Comment: Do you mean $z(3) = 10$, rather than $z(3) = 100$?  If it's really $z(3) = 100$, then your solution doesn't obey the initial condition;  but it does if you want $z(3) = 10$.
Comment: Dear Michael , you are right. z(3)=10. Sorry for the typo
Answer: Let's define $z_\infty = \lim_{x\to\infty} z(x)$.  We currently have a relationship of the form
$$
\frac{z^3(20-z)}{(z-5)^4} = 16 e^{300x-900}.
$$
If we take the limit as $x \to \infty$ on both sides, then $z \to z_\infty$ on the left-hand side, and we conclude that
$$
\lim_{z \to z_\infty}  \frac{z^3(20-z)}{(z-5)^4} = \lim_{x \to \infty} 16 e^{300x - 900}.
$$
This then allows us to figure out what $z_\infty$ is, via a two-step process:

What is the limit on the right-hand side of this equation?
At what values of $z$ does the quantity on the left-hand side approach this same limit?

I'll leave it there, since I don't want to solve your homework for you, but feel free to ask additional questions in the comments.
Comment: @HD239:  There might be another, more rigorous way to solve it;  I'm honestly not sure.  (I'm a physics prof., not a math prof., so we tend to play fast & loose with notation.)  In principle you could solve for $z(x)$ explicitly, but it would involve finding the roots of a quartic polynomial, and the resulting functional form would almost certainly be unilluminating.
Comment: I haven' t heard a expression as yours up to now :) I mean the following notation $z\rightarrow z_\infty$ in the equation $
\lim_{z \to z_\infty}  \frac{z^3(20-z)}{(z-5)^4} = \lim_{x \to \infty} 16 e^{300x - 900}.
$ This is first :) There is no another way to solve?
Answer: You have an autonomous dynamical system on the line. From the equation you see that the fixed points $0,5,20$ lead to constant solutions that can not be crossed due to uniqueness.
On the intervals separated by the stationary points any solution stays inside these intervals and is monotonous. Falling on $(-\infty,0)$, growing on $(0,5)$, again falling on $(5,20)$ and growing again on $(20,\infty)$.
From this qualitative analysis one finds that the solution with $z(3)=10$ follows an inverted sigmoid curve falling from $z(-\infty)=20$ to $z(\infty)=5$.


Model-View-Presenter (or oter GUI architectures) for Complex GUI Library Design in Winforms and WPF

Question: I wasn't quite sure how to title this question or even ask it really, but I will do my best.
I am building a diagram/flowchart style designer which involves (from a very high level) a toolbox of controls, connections, connection points, overlays for editing,etc.
The controls are backed by business objects or components. (i.e. there might be an 'Accounts' components which is represented by a 'Accounts' UI/View component.
Below is a sample mockup of what I am mentioning above.

This is nothign out of control and hundres of applications have similar functionality.
I already have a working version of this (more-or-less), but it was done very poorly by myself (in my opinion) and in order for us to be able to make this extensible so that I can continue developing it our horizontally (additional toolbox support), I need to refactor and do this cleaner.
I have been referencing some articles on common GUI Architectures such as MVP, MVVM, MP, PV,PM,etc.
My concern is that everything I have read so far is very closely related to defining GUI Architectures for CRUD operations. None of these really discuss complex UI library design.
I have been able to find a few articles that give some 'Best Practices' on this topic, but its really not much for me to continue off of.
Thus far, MVP is the closest to what I would imagine would work for this, but I am just not convinced enough to go down that route.
It may not help much, but I figured I could give a brief list of some of the interactions/behaviors that need to be accounted for. Nothing out of the ordinary of what you would see in a diagram or flowchart application.

Controls (backed by business objects, most likely just a reference to the Type to be created at a later time) can be dragged from toolbox to the designer canvas.

Controls can be dragged, removed, and have their state modified (business state).
Connections can be initiated between a source and target component.
Connections can be moved (at both ends) between a soruce and target component.
Multiple designer windows can be open, so we will have to maintain the concept of 'active' designer.

I am still not sure in the case of designing this where I would want to maintain the UI state/logic as well as the business state/logic. Additionally, where would the concept of the 'active designer' be maintained,etc.
UPDATE Apparently, this is another target for SO trolls, so I will try to clarify my question/post.
I am somewhat knowledgeable on the different patterns that are applied for UI design, however It seems they are not versatile enough for library design of complex UI Components. I could be wrong in this. What I want to know is in the case of this particular scenario, from what was discussed above, am I wrong in assuming that going down the route of MVP might not be able to account for complex UI logic?
Comment: You're registered here for almost 5 years now and you still ask a question like this? There is no "best solution". It's up to you how you design your software architecture, we can't decide this for you. Everyone will recommend his approach, but that doesn't fit SO at all. There's no definitive answer and it would be too opinionated.
Comment: The pattern will depend on your target platform: for **WPF** there is no debate this is **MVVM**, for **WinForms** AFAIK **MVP** is the reference pattern. If you use **WPF**: to help you architect your application you have **Prism** but I fear this is overkill in your case, and to ease MVVM development you have dedicated frameworks like **MVVM Light** and **Caliburn Micro**.
Comment: @walther I apologize if it seems that I am asking for a 'best solution', althought I dont recall mentioning those words in my post. What I am trying to understand is if these common UI patterns are able to handle complex UI interactions or if they are generally high level abstract patterns that may not be sufficient.
Answer: All patterns at this level (MVP, MVVM etc.) are suited for pretty much any complexity you'd need. What it can handle is only up to you, you must understand it's still just a pattern, not a framework with some pre-made functions you'd have to use.
Whatever you do however, pick WPF over Winforms, especially when you need complex control over UI.


session variable not increment regularly

Question: I am developing a smartphone web app that is a game of question answer using jquerymobile API.
when a user click on next button that is a anchor tag then i switch to other page and increment the $_SESSION['questionNo'] value. The problem is $_SESSION['questionNo'] value increment from 1 to 4 and then again became $_SESSION['questionNo'] is 1. why it's happening i don't know. Here is my code
<?php session_start();
include("connect.php");
include("header1.php");

$attemp=$_SESSION['questionNo'];
echo $attemp;
$sql = sprintf("select * from question order by pk_id ASC limit %s,%s",$attemp,1);
$result = mysql_query($sql) or die(mysql_error());
$result2=mysql_fetch_array($result);
?>

    Reset

    Score : 50%

    Next

-------------
test.php page
-------------
<!DOCTYPE html>

    <title>My Page</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="css/style.css" media="handheld, screen" rel="stylesheet" type="text/css" />
    <link rel="stylesheet" href="../css/jquery.mobile-1.0a1.min.css"/>

My Title

        <?php
            ++$_SESSION['questionNo'];
            header('Location:startGame.php');
            exit;
        ?>

can any one tell me why $_SESSION['questionNo'] not incrementing regularly???
Comment: Don't import jQuery twice!
Comment:  I only used this code for test.php but not working it. when i refresh the page it automatically increment the value of $_SESSION['questionNo'] from 1-4 then again back to 1.
Answer: Use session_start():
<?php
session_start();
++$_SESSION['questionNo'];
header('Location:startGame.php');
exit;
?>

Comment: i used session_start() but again value drop from 4 to 1
Comment: and if you refresh, it should be kept from 1 to 2, and etc.
Comment: I don't understand what you mean?
Comment: While using session_start() is important, it is also important to note that in the OP's code that portion of code should be moved to the top of the page to avoid any issues with content being sent before the headers.
Comment: I only need to increment the $_SESSION['questionNo'] value that it.
Comment: Here i got terrific problem when i refresh page it automatically increment $_SESSION['questionNo'] value from 1-4 then again back to 1.why this happening any please help me


User profiles as VHDX files - paging operation errors

Question: Hello we have this terminal server on w2k12. Users login and have their profile mounted as virtual disk from VHDX file with filename like this C:\Users\Public\Documents\RDS_UserProfileDisks\UVHD-S-1-5-21-3626241538-2602771230-459845379-52949.vhdx
I can see these as "user disk" with blue icons in disk management.
We started to get incidents from our monitoring related to eventlogs
An error was detected on device \Device\Harddisk5\DR5 during a paging operation.
or
An error was detected on device \Device\Harddisk3\DR74 during a paging operation.
it is always this mounted VHDX from various users (maybe just a few).
Can it be a problem on a physical drive (it's virtual server on VMWare host) or is there some problem in the VHDX file itself? How can I do some check or fix of this drive mounted for user? It does not have a letter. Can I mount the VHDX and assign it a letter when user is not logged on and perform chkdsk on it?
Answer: From technet:

This Error event indicates that an error was detected on a physical
  hard disk during a disk paging operation. This problem occurs if an
  I/O operation to a hard disk is unsuccessful. If an I/O operation to a
  hard disk is unsuccessful, the Windows operating system logs Event ID
  51 in the System log.

So, somehow your VHDX file has I/O operation failing. What you can do now?

be sure that your underlying physical disks/controller are healthy
check VHDX file consistency using this powershell command: Get-VMHardDiskDrive <vmname> | test-vhd (give a look here for more information)
check filesystem consitency inside the VHDX file, using chkdsk
Comment: more questions: how do I see which logged user is having which VHDX file mapped. Can I do this test on a live mounted VHDX?
Comment: unfortunately there is no Hyper-V role installed there and we don't seem to have it on any other server... so I can't use these cmdlets :-\


How to implement ui-grid with trailing infinite scroll

Question: I have a requirement, to add infinite scroll to my ui-grid component. Following this tutorial I have successfully implemented my scrolling grid, but when it comes to performance, the results do not suit my requirements, so I need to add trailing to this implementation, meaning I need to load more data the I display on the grid.
e.g. call the backend for 100 elements and display in one scroll only 20, in this way I limit the number of calls to the backend.
So how is the best way of doing this using this component?
Answer: You can tune you performance by changing infiniteScrollRowsFromEnd in gridOptions.
This way you choose how far from the bottom new data should be requested. Then again the amount of rows to download is chosen by you.
If you choose a small number for the former and a big one for the latter you will have few calls to your service but the user may experience some waiting.


Android which is better for service stopself or never stopping it

Question: I have in my project services that start only once and inside the service there is a thread that runs every second or so.
And then there is some services that after they finiah their procedure they call stopself and then they are started again for elsewhere.
My question is which of these structures are better for a service and why?
Comment: why you keep running a service in the background if you don't use it?
better stop it and start it only when you need it.
Comment: I do use it. It just calls a method once and terminates and does that again. But I need the results fron that meethod everytime
Comment: Have you looked into using an **IntentService**?  It uses a worker thread by default, and does not need `stopSelf()` to be called.
Answer: If you often start and finish Service, try using IntentService
It automatically shuts down after work finished.
Developer Guide
Answer: What k0sh said.  If your service is running, it is using battery.  If you don't need it running, stop it and save battery.
The difference between a running service and a stopped service is the likelihood that the process running it will be killed.  A running service has a fairly high priority (low oom_adj).  Android will try not to kill it off.  A service that is not running has no affect on the priority of its owning process.  If there is no other reason to keep that process around, Android will kill it, when it needs space.
Even a running service, though, will be reaped, eventually.  There is no way to keep a process running forever.
Comment: You can't.  It is, literally, impossible to keep anything running all the time, on an Android device.  Have a look at the AlarmManager
Comment: But I do need it to keep running in background all the time
Comment: ~"**There is no way to keep a process running forever**".  Actually, `zygote` process runs forever...
Comment: So does rild.  Irrelevant.


Can someone help? Sending notifications to all users or some users in django forms

Question: I want to send a single notification message to multiple users or all users. I have tried many to many fields but the sent to id won't save the i.d's of the users that i have sent the message to.
Models.py
class Notifications(models.Model):
    id=models.AutoField(primary_key=True)
    sent_to = models.ManyToManyField(CustomUser)
    message = models.TextField(null=True)
    message_reply = models.TextField(null=True)
    created_at=models.DateTimeField(auto_now_add=True)
    updated_at=models.DateTimeField(auto_now=True)

Views.py
def add_notification(request):

    notifs = Notifications.objects.all()
    users = CustomUser.objects.filter(is_staff=True)

    if request.method == 'POST':
        form = AddNotifForm(request.POST)
        if form.is_valid():
            instance = form.save(commit=False)
            instance.message_reply = "none"
            instance.save()
            sent_to = form.cleaned_data.get('sent_to')
            messages.success(request, f'Message has been successfully sent .')
            return redirect('add_notif')
    else:
        form = AddNotifForm()

    context={

        'notifs' : notifs,
        'form' : form,
        'users' : users,
    }

    template_name ='main-admin/add-notif.html'
    return render(request, template_name, context)

Forms.py
class AddNotifForm(forms.ModelForm):

    sent_to = forms.ModelMultipleChoiceField(
            queryset=CustomUser.objects.filter(is_staff=True).exclude(is_superuser=True),
            widget=forms.CheckboxSelectMultiple,
            required=True)

    class Meta:
        model = Notifications
        fields = ['sent_to', 'message']

Answer: From the docs:

every time you save a form using commit=False, Django adds a save_m2m() method to your ModelForm subclass. After you've manually saved the instance produced by the form, you can invoke save_m2m() to save the many-to-many form data.

So you'll have to call save_m2m() after instance.save() if you are using commit=False:
        instance = form.save(commit=False)
        instance.message_reply = "none"
        instance.save()
        form.save_m2m() # <-- Add this

Comment: This worked for me and thank you for the tip
Comment: But now how can I call the notifications for each user in a datatable since it's not set on notification model?
Comment: Not sure if I understand what you mean, but you can get all the users from the notification object like: `sent_to_users = notification.sent_to.all()`. Otherwise it might be better to write a new question for it
Comment: I'd get an error 'ManyToManyDescriptor' object has no attribute 'all', if i use that notifications.sent_to.all()
Comment: It will only work for one instance of notification (the result of `get`, `first`, `last`, etc.). So for example: `n = Notification.objects.first(); n.sent_to.all()`
Comment: I see, so i cannot show in a table all of the notification for that user based on their i.d?
Comment: You can, by using: `Notification.objects.filter(sent_to=request.user)`
Comment: I tried this and it does not show the notification even if there is an entry in the notifications_sent_to table referring to the logged in user
Comment: I just tried it out and it works. Are you able to share the code you used to try this out in your other question? Also please show the id of the logged in user, as well as the entry in the `notifications_sent_to` table
Comment: Wait ill post the codes again


How to add a term image to node

Question: I have a nodes, and a few vocabularies to choose terms from. I would like to show images of terms from specific vocabulary in nodes (If node is associated with term from specific vocabulary, it would show image from that terms field). What would be the best (most "Drupal") approach to this? :)
Answer: One way to do it -- if you don't want to create/mess with the theme template files for your content type, would be to display the corresponding tag image via a view.
Here are the steps to doing that:

I'm assuming you already have your vocabulary set up properly and you have the image field added to it (can be done at admin/structure/taxonomy/[YOUR VOCAB ID]/fields) and some terms have been populated with their corresponding images.
Create a new view with a block display, and set it to apply only to the relevant content types

Add a term relationship to your view, so you can access the vocab/term fields, and not just the node fields!!

Once you've done that, go into the fields you want to pull for each node.  I'd remove the 'Title' field that's added by default and only add the field that represents the image associated with your term.  It should be somewhere under the 'Taxonomy term:....' section of the field list.
Make sure that you set it to use the relationship you created above

Finally, since we'll want this block to take its cue of which image to display based on which node it's on, let's add a contextual filter.  Under the 'Advanced' section --> 'Contextual filters', add the 'Content: Nid' one and make sure you set it up to take its NID from the page it appears on if a filter isn't present in the URL

All done!  Go to one of the relevant pages and test.  Of course, you'll have to enable the block via contexts or the block admin page (admin/structure/block) first, since it's not placed anywhere by default.  Display the block on the second sidebar, in the actual content section -- anywhere you want.

Let me know if this helps!!
================ EDIT =====================
Solution 2 (upon request)
To do this through your template file, go ahead and copy your regular node.tlp.php file and rename it node--[YOUR CONTENT TYPE MACHINE NAME].tpl.php
Then, right under or above the content, insert the following code:
<code>$term=taxonomy_term_load($node->field_thats_term_reference['und'][0]['tid']);
$image_field=field_view_field('taxonomy_term', $term,'field_main_image');
print render($image_field);
</code>
Just substitute 'field_thats_term_reference' with the name of your term reference field, and substitute 'field_main_image' with your image field name.
That'll do the print out.  You can place this anywhere you want.  If you want to customize how the print out actually looks, just do a dpm($image_field) once you've set that variable (must have the devel module installed), and you can see all the parts of that field and how to get to them if you want to print them out separately as opposed to the default way render() prints it all out.  I think that part is beyond the scope of this question, but it should get you started!
Comment: I think there should be if($term=taxonomy_term_load($node->field_thats_term_reference['und'][0]['tid'])) { /* the rest */ } otherwise I'm getting error :) (info for readers) .
Comment: Alright, you've talked me into it.  I've edited the answer and included that....
Comment: Thanks! That works, but I'm also interested in achieving this by creating/manipulating template files. Could you add something about it to your answer? :) That would be really epic answer ^^ .
Comment: Yep, you're totally right.  If this term is not required for the content type...  Very nice catch!

How to add a term image to node


Drupal versus with Omni Update: Should I move from Drupal to Omni Update?

Question: Use Case

Current (aging) IT website built on Drupal 5.
Most people hate this website because the theme is awful and adding content is painful.
An upgrade to Drupal 6 and a theme / module updates are what are needed. (Not considering Drupal 7 until more modules are available.)
Some of our leadership thinks we need to switch platforms anyway.

Argument

What are the pros of sticking with Drupal versus switching to Omni Update?
What are some pro Drupal buzzwords that nontechnical manager-folk will understand?
What is your best argument for selling Drupal to a prospective client?
Answer: I think you might have answered your own question: "it will turn into a LOT of work if they decide to switch to the proprietary platform". Work = time = money, and that is manager-speak.
Answer:
What are the pros of sticking with Drupal vs. switching to Omni
  Update?

There is a site called http://drupal.stackexchange.com, but there is no http://omniupdate.stackexchange.com. Just kidding of course, but still, there's some truth behind this - I bet that Drupal has better support than a proprietary platform.
Now we're waiting for Drupal 8; this means we have a lot of people with good knowledge about 6 who could perform the upgrade fine (maybe some reading is needed, but still). Show the managers the difference between "stock" Drupal 5 vs. 6 vs. 7. Try to show them some of the developments underway. Show them the big guys doing crazy stuff with Drupal; mention Acquia for example, show Gardens. Mention that Drupal is good enough for Ubuntu sites, for the Twitter dev site and so on.
If none of the above works, just mention that it's waaaaaay cheaper to perform an upgrade than to move to a proprietary software. Perhaps even if you have to pay for other guys to do the upgrade, because you will have to move content anyway and it's easier (= less workhours) with a Drupal upgrade.
Comment: Thank you for your answers. I have already performed the upgrade to Drupal 6, this is about communicating the value to the project stakeholders. It really is a time issue too, it would take 700-1000 hours to transfer to a new system and I'm offering something upgraded _right now_


Group of order $pq, p \leq q, p \not\mid q - 1$ is abelian

Question: This is an example from D&F before Cauchy's theorem and before the Sylow theorems.
They first note that $Z(G) = \{e\}$, as otherwise $G/Z(G)$ is cyclic and therefore abelian. Sure.
They then say that if every nonidentity element has order $p$, then the centralizer of every nonidentity element has index $q$, i.e. order $p$. But I'm having a blind spot and I'm not able to see why the centralizer of such an element can't have order $q$.
Comment: Because $p$ must **divide** the order of the centralizer by Lagrange.
Comment: Because it contains itself.
Comment: @the_fox Maybe if the centralizer had order $q$ then this would mean that there's a cyclic subgroup of order $q$, and hence an element of order $q$?
Comment: If $C$ is a cyclic subgroup of the group $G$, then $C_G(C) \geq C$. Thus the centralizer of an element of order $p$ in a group of order $pq$ can't possibly have order $q$.
Comment: @the_fox I agree that the centralizer of an element of order $p$ must have order $\geq p$. But why not $q$?
Answer: Let $x$ be an element of order $p$. (Thus, $x \neq e$.)
The centraliser $C_G(x)$ is the subgroup $C_G(\langle x\rangle)$ (by definition).
Now, note that $\langle x\rangle$ is abelian and hence, $\langle x\rangle \le C_G(x).$
This gives us that $p \mid |C_G(x)|$. (Lagrange's theorem)
Thus, $|C_G(x)| = p$ or $|C_G(x)| = pq$.
However, if the order were $pq$, then we would have $C_G(x) = G$. This would imply that every element of $G$ commutes with $x$.
In turn, this would give us that $x \in Z(G)$. This contradicts the fact that $Z(G) = \{e\} \not\ni x$.
This leaves with the sole possibility that $|C_G(x)| = p$.


How to access controller ViewData and TempData from its child object - notification provider implementation

Question: I'm trying to build a notifications provider (alerts) for my application. Currently I only need to generate notifications between requests, but having this functionality wrapped in a provider will allow me to hook it up to the database later.
I have 3 types of notifications:
public enum NotificationType
{
    Success,
    Error,
    Info
}

and a Notification object:
public class Notification
{
    public NotificationType Type { get; set; }
    public string Message { get; set; }
}

I would like to put all notifications in List<Notification> and load it into ViewData["Notifications"]
I could then use the helper to read ViewData["Notifications"] and render it:
I want to implement my own NotificationProvider which would maintain the List<Notification> object.
I want the provider to read TempData["Notifications"] and load it into List<Notification> Notifications variable. I could then load notifications into ViewData["Notifications"] for my helper to use.
Code below isn't working but I think it shows what I'm trying to do.
public class NotificationProvider
{
    public List<Notification> Notifications { get; set; }

    private Controller _controller;

    public NotificationProvider(Controller controller /* How to pass controller instance? */)
    {
        _controller = controller;

        if (_controller.TempData["Notifications"] != null)
        {
            Notifications = (List<Notification>)controller.TempData["Notifications"];

            _controller.TempData["Notifications"] = null;
        }
    }

    public void ShowNotification(NotificationType notificationType, string message)
    {
        Notification notification = new Notification();

        notification.Type = notificationType;
        notification.Message = message;

        Notifications.Add(notification);

        _controller.TempData["Notifications"] = Notifications;
    }

    public void LoadNotifications()
    {
        _controller.ViewData["Notifications"] = Notifications;
    }
}

And in each controller a NotificationProvider instance:
public class HomeController
{
    private NotificationProvider notificationProvider;

    public HomeController()
    {
        notificationProvider = new NotificationProvider(/* Controller instance */);
        notificationProvider.LoadNotifications();
    }
}

Question:
How do I pass the controller instance to NotificationProvider class so it can access TempData and ViewData objects. Or if it's possible, how can I access those objects directly from NotificationProvider instance?
Answer: I think you only want to pass this, like that. Also, back from comments, TempData will only be available in actions:
public class HomeController
{
    public ActionResult Index()
    {
        var notificationProvider = new NotificationProvider(this);
        notificationProvider.LoadNotifications();
        return View();
    }
}

Comment: Thanks. That worked. I can't believe it was that simple. I'm wondering though why did you edit out that bit about TempData not being available in constructor? I can't get it to work when placed in controller's constructor but it works great in an action.
Comment: I'll replace that then. I just couldn't run the sample and verify that it really wasn't available.
Comment: It isn't. But it's available in `protected override void OnActionExecuting(ActionExecutingContext filterContext)` :P