iphone: autoreleasing an object multiple times

Question: what happens if i retain an object multiple times. Then, will autoreleasing it once, delete it from the memory when the autorelease pool is drained; or do i have to autorelease it as many times as i retained it ?
Answer: Autorelease schedules an object to be released once in some time in future (i.e. when current autorelease pool is drained). So if you retain an object several times you need to (auto)release it the same number of times to compensate that


How find the value of the $x+y$

Question: Question:

let $x,y\in \Bbb R $, and such
  $$\begin{cases}
3x^3+4y^3=7\\
4x^4+3y^4=16
\end{cases}$$
Find the $x+y$

This problem is from china some BBS
My idea: since
$$(3x^3+4y^3)(4x^4+3y^4)=12(x^7+y^7)+x^3y^3(9y+16x)=112$$
$$(3x^3+4y^3)^2+(4x^4+3y^4)^2=9(x^6+y^8)+16(y^6+x^8)+24x^3y^3(1+xy)=305$$
then I can't  Continue
Comment: Would you double check the source, and if possible, link to it online somewhere? As JimmyK4542 points out, if we cheat and use technology, we can see that $x+y$ can take _two_ different values. So it seems questionable that this problem is worded correctly. Either that, or there just was a mistake by its author in the first place.
Comment: It appears that there are two real solutions $(x,y)$ which yield two different values of $x+y$. http://www.wolframalpha.com/input/?i=3x%5E3%2B4y%5E3+%3D+7%2C+4x%5E4%2B3y%5E4+%3D+16
Comment: By $R$ you mean $\mathbb{R}$?
Comment: You are basically asking us for the intersection of two [superellipses](http://en.wikipedia.org/wiki/Superellipse), of which the latter is similar to a [squircle](http://en.wikipedia.org/wiki/Squircle).
Comment: @Squirtle,yes, That's mean
Comment: When complaining about the _two_ solutions $x+y$ , suppose instead $3x^3+4y^3=7$ and $4x^4+3y^4=7$ . Then trivially $x=y=1$ . But I don't think the OP wants to ask such a simple question.
Answer: Assuming the question is typed correctly as shown, there are two unique real solutions.  Let $$\begin{align*} u(z) &= -983749-111132z^3+786432z^4+71442z^6-196608z^8-20412z^9+18571z^{12}, \\ v(z) &= -178112-351232z^3+186624z^4+301056z^6-34992z^8-114688z^9+18571z^{12}. \end{align*}$$ These polynomials have exactly two distinct real roots; let $r(u,+)$, $r(u,-)$ be the positive and negative real roots of $u$, and $r(v,+)$, $r(v,-)$ be the positive and negative real roots of $v$, respectively.  Then $$(x,y) \in \{(r(u,-),r(v,+)), (r(u,+),r(v,-))\}$$ are the desired solutions.  The sum $x+y$ can then be expressed by the solution to a third polynomial  $$f(z) = 819447-537600z-8998752z^3+3291428z^3+22132992z^4-17875200z^5+3163146z^6+1042512z^8-437500z^9+18571z^{12},$$ for which there are again two real roots, both positive.  All of these polynomials are irreducible.  So I highly doubt that this is a problem that can be reasonably solved by hand.
Comment: Maybe an interesting adaptation of this question: what conditions must the integer coefficients of the system satisfy in order to have rational solutions?
Comment: @HandeBruijn: Given that the bounty asks if this can be solved by hand, it seems to me that this answer is entirely reasonable in proceeding analytically.
Comment: What's the big deal if you can't solve by hand, indeed, but there exist things in the world, called computers, for quite some time? And it seems that you have made the problem far more complicated than the original.
Comment: @HandeBruijn You seem to be implying that I have unnecessarily complicated the answer, when I have done nothing of the sort.  The fact is that the solution of a polynomial system in general involves polynomials of higher degree than the original system; e.g., just try solving $$\begin{align*} x^2 + 2xy + 3y^2 &= 5, \\ x^2 - 3xy + 2y^2 - 4x &= 1. \end{align*}$$  Two simple conic sections.  My point is that there is no "simple" way to get at the answer.  What I have written above is about as simple as it gets.
Comment: @Semiclassical +1 Indeed.  And instead of rational, I'll even settle for "polynomial of lower degree," or to be completely generous, "solution by radicals."
Comment: I think I may propose this as another question: which superellipses with rational coefficients have rational roots? Reducible roots? Solvable roots? I imagine it's a topic within algebraic geometry.
Comment: @heropup: See the answer by 'mwomath' as an illustration of what happens if someone has no idea what the numbers are like, numerically.
Comment: @Semiclassical: As long as "proceeding" does indeed exist, you'll find nothing but agreement on my side.
Comment: @HandeBruijn: Indeed. Hence why I wonder about the solubility conditions of such systems.
Comment: If either of you are interested, here's the [question](http://math.stackexchange.com/questions/868635) I made. @HandeBruijn
Comment: Perhaps, that's trivial - but how did you get $u$ and $v$?
Answer: Here comes a drawing from a credible (Delphi Pascal) source (-:

Viewport:

  xmin := -4; xmax := +4;
  ymin := -4; ymax := +4;

Color assignment:
$$
\begin{cases}
\color{red}{3x^3+4y^3=7}\\
\color{green}{4x^4+3y^4=16}
\end{cases}
$$
Hope this helps. (Now thinking about the rest ..)
EDIT. A parameter representation for the curve $\;3x^3+4y^3=7\;$ is:
$$
x(t) = -\sqrt[3]{\frac{t}{3}} \qquad ; \qquad y(t) = \sqrt[3]{\frac{t+7}{4}}
$$
This turns the problem into seeking zeroes of a one-dimensional function:
$$
   f(t) = 4 x^4(t) + 3 y^4(t) - 16
$$
Standard numerical methods can be employed for this purpose.
Newton-Raphson and
Regula Falsi
have been successful here. Our (double precision) results are:
$$
t = 3.56874527617414 \quad \Longrightarrow \quad
(x,y) = ( -1.05957433921527 , +1.38246606572819 ) \\
t = -8.23503156460535 \quad \Longrightarrow \quad
(x,y) = ( +1.40017183631184 , -0.675884813969605 )
$$
Giving, respectively:
$$
x+y = 0.322891726512912 \\
x+y = 0.724287022342236
$$
ALGORITHM (Delphi Pascal) :

program RF;
type
  funktie = function(t : double) : double;
function regula_falsi(d1,d0,eps : double; F : funktie) : double;
{
  Regula Falsi
}
var
  OK : boolean;
  d2 : double;
begin
  d2 := d0;
  while abs(F(d2)) > eps do
  begin
    d2 := d1 - F(d1)*(d0 - d1)/(F(d0) - F(d1));
    if F(d2) = 0 then Break;
    OK := (F(d2)F(d1) < 0);
    if not OK then
    begin
      d1 := d2;
    end else begin
      d0 := d1; d1 := d2;
    end;
    Write(d2,' : ',F(d2),' ; Press Enter'); Readln;
  end;
  regula_falsi := d2;
end;
function power(x,r : double) : double;
var
  M : double;
begin
  M := 0;
  if x > 0 then
    M := exp(rln(abs(x)));
  if x < 0 then
    M := -exp(r*ln(abs(x)));
  power := M;
end;
function original(t : double) : double;
{
  Function itself
}
var
  x,y,f : double;
begin
  x := -power(t/3,1/3);
  y :=  power((t+7)/4,1/3);
  f := 4*sqr(sqr(x))+3*sqr(sqr(y))-16;
  original := f
end;
procedure Calculate(x1,x2 : double);
const
  eps : double = 1.E-14;
var
  t,x,y,t1,t2 : double;
begin
  t1 := 3*sqr(x1)*x1;
  t2 := 3*sqr(x2)*x2;
  t := Regula_Falsi(t1,t2,eps,original);
  Writeln(t);
  x := -power(t/3,1/3);
  y :=  power(t/4+7/4,1/3);
  Writeln(x,' +',y,' =',x+y);
end;
begin
  Calculate( 1.0, 1.5);
  Writeln;
  Calculate(-1.5,-0.5);
end.

Note that the only place that is truly machine dependent is
the stopping criterion with 'eps'. As for the rest, the algorithm is
quite general. Also take note of the rather crude starting values $(1.0,1.5)$ and $(-1.5,-0.5)$ for $x$ at the end of the code, emphasizing the robustness of this algorithm.
Comment: @heropup: That a numerical solution would be inferior to an analytical one _that cannot be found_ (see _all_ of the other answers), that escapes me. Sorry.
Comment: @heropup: About the "Anyone can get", oh well, you're quite right. I could saved myself much effort by simply invoking MAPLE: "fsolve({3*x^3+4*y^3=7,4*x^4+3*y^4=16},{x,y},x=1.0..1.5 or x=-1.5..-0.5);" . How has "by hand" evolved these days ..
Comment: Your numerical solution fails to establish whether or not the solution set is expressible analytically, and therefore is unsatisfactory from a mathematical viewpoint, much in the same way that someone might ask how to obtain a closed form expression for $$\sum_{k=1}^\infty \frac{1}{(2k+1)(5k+3)}.$$  Anyone can get a numerical approximation to the above by naively adding terms; others can use more sophisticated methods to get faster convergence; but what is *mathematically* interesting is the analytic solution.
Comment: On the other hand, each number of Regula Falsi iterations in the above algorithm is less than $20$ ! So I could have done them with a _hand_ calculator. Shouldn't this count as "by hand" ?
Answer: Defining $z:= x+y$, the equations become
$$\begin{cases}
3x^3+4(z-x)^3=\phantom{1}7\\
4x^4+3(z-x)^4=16
\end{cases}$$
Using the method of resultants (which could conceivably be done "by hand", but I used Mathematica because life's too short) to eliminate $x$, we confirm @heropup's result:
$$\begin{align}
0 &= 819447 - 537600 z - 8998752 z^2 + 3291428 z^3 + 22132992 z^4 \\ &-
 17875200 z^5 + 3163146 z^6 + 1042512 z^8 - 437500 z^9 + 18571 z^{12} \quad (\star)
\end{align}$$
Solving an irreducible $12$th-degree polynomial equation is tricky at best. Again using Mathematica, the two real roots of $(\star)$ are found to be
$$z=0.322892\dots \quad\text{and}\quad z=0.724287\dots$$
If we abstract the equations like this ...
$$\begin{cases}
a_1 x^3 + b_1 (z-x)^3=c_1\\
a_2 x^4 + b_2 (z-x)^4=c_2
\end{cases}$$
... then the corresponding resultant is ...
$$\begin{align}0 &= c_1^4\;(a_2 + b_2)^3 - c_2^3\;(a_1 - b_1)^4 \\
&- 12 z \; (a_1 - b_1)^2 \; (a_1 b_2 + a_2 b_1)\; c_1 c_2^2 \\
&+ \cdots \\
&- 24 z^5\;(a_1 b_2 + a_2 b_1) \; (a_1 a_2 b_1 + 2 a_2 b_1^2 + 2 a_1^2 b_2 +
   a_1 b_1 b_2) \; c_1 c_2 \\
&+ \cdots \\
&- 4 z^9 \; ( a_1 b_2 + a_2 b_1)^3 \;c_1 \\
&+ z^{12}\; ( a_1^4 b_2^3 + a_2^3 b_1^4 )
\end{align}$$
Observations:

A number of coefficients vanish under the assumption $a_1 b_2 + a_2 b_1 = 0$, although this doesn't really help much, because the polynomial remains irreducible still and degree $12$.
We can reduce the degree to $9$ with the relation $a_1^4 b_2^3 + a_2^3 b_1^4 = 0$, but that's also not particularly helpful.
We can eliminate the constant term if $c_1 = |a_1 - b_1| c^3$ and $c_2 = (a_2 + b_2) c^4$ for some $c$. In the original problem, with $a_1 = b_2 = 3$ and $b_1 = a_2 = 4$, this gives $c_1 = c^3$ and $c_2 = 7 c^4$. If $b_2$ had a sign-change to $-3$, then $c_1 = c^3$ and $c_2 = c^4$, which for $c=2$, give $8$ and $16$ ... almost the $7$ and $16$ of the original problem. Even so, polynomial $(\star)$ only reduces to $11$th degree.

If there's something remarkable about the solutions to this problem, I'm not seeing it.
Comment: As with my comments in @heropup 's answer, I'm [curious](http://math.stackexchange.com/questions/874511/) whether there's some criteria for the integers on the RHS's under which that equation becomes reducible...
Comment: @Semiclassical: With $a_1=b_2=3$ and $a_2=b_1=4$, the polynomial $(\star)$ becomes $$\begin{align} 0 &= (343 c_1^4 - c_2^3) - 300 c_1 c_2^2 z - 11478 c_1^2 c_2 z^2 + 9596 c_1^3 z^3 + 86457 c_2^2 z^4 \\ &- 159600 c_1 c_2 z^5 + 64554 c_1^2 z^6 + 65157 c_2 z^8 - 62500 c_1 z^9 + 18571 z^{12}\end{align}$$ Perhaps you can identify a reducibility criterion in there somewhere. :)
Comment: That is the question, isn't it. (Which is why I asked it as a new question, since stuff like reducibility/solvability isn't really in my wheelhouse.)
Comment: Note that the resultant in $x$ in the case $a_1=b_2=3$ and $a_2=b_1=4$ is a bit nicer (only 8 terms). Still pretty terrible, but I'll take what I can get.
Answer: Another idea for you to think about. We have:
$$\begin{cases}
3x^3+4y^3=7 \\
4x^4+3y^4=16
\end{cases}$$
Break it as:
$$\begin{cases}
3x^3+3y^3 + y^3=7 \\
x^4 + 3x^4+3y^4=16
\end{cases}$$
and factor:
$$\begin{cases}
3(x+y)(x^2 - xy + y^2)=7 - y^3\\
3(x+y)(x^3 - x^2y + xy^2 - y^3)=16 - x^4
\end{cases}$$
And so: $$x+y = \frac{1}{3}\frac{7 - y^3}{x^2 - xy + y^2} = \frac{1}{3}\frac{(2-x)(8+4x+2x^2+x^3)}{x^3 - x^2y + xy^2 - y^3}$$
Comment: That's fine. But the question is: how to proceed then?
Comment: Interestingly, I did the same thing on scrap paper a few days ago when I first saw this. I was hoping that I could do something with the expression for $x+y$ by using other manipulations of the given equations, but I didn't get anywhere.
Comment: I also couldn't do anything more of the sort. But I posted this answer, anyway, in hopes that OP might have some more ideas bases on this. Maybe he hadn't seen this approach. I understand the downvotes, and in fact, I never expected the answer to get the upvotes it got. I just wanted to add something to the question, since no one had said it yet.

How find the value of the $x+y$


Submission handler for the user registration form doesn't work

Question: I'm working on a Drupal 7 portal. I added a custom field to the registration form and I would like to get hold of custom field value when the registration form is submitted and before it is stored in the database.
I'm trying to use the submission handler for the registration form and print the content of $form and $form_state, but those values never get printed as message. I installed the Devel module as well.
function user_register_form_submit($form, &$form_state) {
    drupal_set_message('
'. print_r($form, 1) .'
');
    drupal_set_message('
'. print_r($form_state, 1) .'
');
    drupal_set_message(t('An info message from user_register_form_submit'), 'error');
}

I appreciate any input on what the issue could be.
Answer: In hook_form_alter use foloowing code

function MODULENAME_form_alter(&$form, $form_state, $form_id) {
if($form_id == 'user_register_form'){
    $form['#submit'][] = 'module_custom_form_submit';
   }
}

after that use

function module_custom_form_submit($form, &$form_state) {
    // Do whatever you want.
}

Comment: The question is _Why isn't the content of `$form` and `$form_state` printed?_
Comment: Are you talking about my solution?
Comment: I am commenting on your answer. The OP is asking a different question. (_I'm trying to use the submission handler for the registration form and print the content of `$form` and `$form_state`, **but those values never get printed as message**. I installed the Devel module as well. I appreciate any input on what the issue could be._)
Comment: The reason nothing is printed might be `user_register_form_submit` is not properly registered as a submission handler. Hence Jeetendra Kumar's answer.
Comment: @KirillShabunov This answer doesn't make clear the reason of the suggestion. If the OP doesn't understand what he is doing wrong, this answer doesn't explain what is wrong in the OP's code.
Comment: This code is working for me. I am using the same code.
Answer: There are two issues in the shown code.

Simply defining a function is not sufficient for Drupal to consider it a form submission handler, not even if the function name ends with _form_submit. To add a new form submission handler, the module you are developing needs to implement hook_form_alter() or hook_form_FORM_ID_alter(), and add a new form submission handler.
function mymodule_form_user_register_form_alter(&$form, &$form_state) {
  $form['#submit'][] = 'mymodule_user_register_submit';
}

To debug a form submission handler you should use watchdog(). Once the Database logging module is installed, on admin/reports/dblog you can read all the messages added with watchdog().


Drupal 7: View filters impact on performance

Question: Does having multiple view filters affect the overall performance of the site. for example having a category and search filter on main pages of articles and galleries?
Answer: In general having more views will effect the performance of your site. However you can check the view query / render etc at the bottom of the view edit pages which should give you insights into what degree they effect performance. You can also cache views but it means there will be a lag on content updates being shown by the view.
In general you will also find more modules you add to drupal will have a performance impact although it could be slight. Even adding views to pages will add js and css and thus the more page weight so it will take longer to download. Also views run will have more db queries and have a performance impact on the database.
Was there something in particular you were looking for?
Comment: As for views filters, they'll of course only affect performance if used.
Comment: thanks guys.@WestieUK - i have a site with a lot of views filters so was wondering whether to leave them on or remove them. what if i add apache solr?
Comment: The amount of views or filters is not always a performance problem & you should weigh up the functionality / performance cost. Why do you think the views in particular are an issue? You should check all yours views performance to see if any stand out as being slow. If so you can play with the filters and caching to bring the query & render times down to acceptable levels. You may even need to apply an index in your db. If you are finding you site is running slow there is a great deal you can do with Drupal in terms of caching, compression or even by using tools like yslow to bench mark.


How to find a matrix $X$ such that $X+X^2+X^3 = \begin{bmatrix} 1&2005\\ 2006&1 \end{bmatrix}$?

Question:
Find a matrix $X \in M_{2}(\mathbb Z)$ such that $$X+X^2+X^3=\begin{bmatrix} 1&2005\\ 2006&1\end{bmatrix}$$

My try:
Let
$$X=\begin{bmatrix}
a&b\\
c&d
\end{bmatrix}$$
where $a,b,c,d\in Z$
then
$$X^2=\begin{bmatrix}
a^2+bc&ab+bd\\
ac+cd&bc+d^2
\end{bmatrix}$$
then $$X^3=\begin{bmatrix}
a^3+abc+abc+bcd&a^2b+b^2c+abd+bd^2\\
a^2c+acd+bc^2+cd^2&abc+bcd+bcd+d^3
\end{bmatrix}$$
so
$$X+X^2+X^3=\begin{bmatrix}
a^3+2abc+bcd+a^2+bc+a&a^2b+b^2c+abd+bd^2+ab+bd+b\\
a^2c+acd+bc^2+cd^2+ac+cd+c&abc+2bcd+d^3+bc+d^2+d
\end{bmatrix}$$
then we have
$$\begin{cases}
a^3+2abc+bcd+a^2+bc+a=1\\
a^2b+b^2c+abd+bd^2+ab+bd+b=2005\\
a^2c+acd+bc^2+cd^2+ac+cd+c=2006\\
abc+2bcd+d^3+bc+d^2+d=1
\end{cases}$$
Note $2005=5\cdot 401 $ is prime number,so
$$b(a^2+bc+ad+d^2+a+d+1)=2005$$
we can $b=\pm 1$ ,or $b=\pm 2005$ ,or $b=\pm 5$ or $b=\pm 401$
and note $2006=2\times 1003$
then $c=\pm 2$ ,or $c=\pm 1003$or $c=\pm 1$,or $c=\pm 2006$
so following is very ugly.  But I can't.Thank you ,maybe this problem have other nice methods,Thank you
Comment: How have you ruled out $c=\pm 2006$ and $c=\pm 1$?
Answer: There's no such $X$, even with rational entries.
If there were, then it would have an eigenvalue that's either
rational or a quadratic irrationality.
But if $\lambda$ is an eigenvalue of $X$ then
$\lambda + \lambda^2 + \lambda^3$ is an eigenvalue of
$\left[\begin{array}{cc}1&2005\cr2006&1\end{array}\right]$.
But those eigenvalues are the roots $x = 1 \pm \sqrt{2005\cdot 2006}$ of
$(x-1)^2 = 2005 \cdot 2006$, and the polynomial
$(\lambda^3+\lambda^2+\lambda-1)^2 - 2005 \cdot 2006$
turns out to be irreducible, so none of its roots can be
the eigenvalue of a $2 \times 2$ matrix with rational entries, QED.
Comment: Actually an "exact formula" *is* possible, but you probably
don't want to see it...  Diagonalize
$M = \left[\begin{array}{cc}1&2005\cr2006&1\end{array}\right]$,
then find the real solution $\lambda$ of $\lambda + \lambda^2 + \lambda^3 = \mu$
for each of the eigenvalues $\mu = 1 \pm \sqrt{2005\cdot 2006}$,
and make those $\lambda$'s the eigenvalues of $X$ with the same eigenvectors as for $M$.
The equations $\lambda + \lambda^2 + \lambda^3 = \mu$
are cubic in $\lambda$, and thus solvable in radicals,
but the solution isn't pretty to say the least!
Comment: @nanchangjian Best I can tell you is that Mathematica quickly finds that there is a unique real matrix solution given approximately by $a = 0.00660507, b = 12.2508, d = 12.2574, c = 0.00611011$.  The general solution suggests an exact formulation is not possible, and you'd be forced to go for numerical approximations.
Comment: [Approximation](http://www.wolframalpha.com/input/?i=%7B%7B-sqrt%282005%2F2006%29%2C+sqrt%282005%2F2006%29%7D%2C+%7B1%2C+1%7D%7D*%7B%7B-12.9238170830391%2C0%7D%2C%7B0%2C+12.2624366772719%7D%7D*%7B%7B-sqrt%281003%2F4010%29%2C+1%2F2%7D%2C+%7Bsqrt%281003%2F4010%29%2C+1%2F2%7D%7D) of what @NoamD.Elkies explained.
Comment: Oh,Thank you, If we this question Find the real matrix $X\in M_{2}(R)$,How prove it?
Answer: If an integer matrix solution exists, then with modulo 2 arithmetic and with $X=Y+I$, the equation
$$
(Y+I)+(Y^2+I)+(Y^3+Y^2+Y+I) = \pmatrix{1&1\\ 0&1}
$$
is solvable over $GF(2)$, meaning that
$$
Y^3 = \pmatrix{0&1\\ 0&0}.
$$
But this is impossible because the square of every $2\times2$ nilpotent matrix must vanish. Therefore the matrix equation in the OP's question has no integer matrix solution.
Answer: The Elkies's argument: -more generally- let $K$ be a field, $A\in M_k(K)$ and $P\in K[x]$ of degree $d$; we consider the equation $(*)$ $P(X)=A$. If $(*)$ has a solution $X\in K$, then necessarily, the polynomial of degree $kd$: $\det(A-P(x)I_k)$ has a factor of degree $\leq k$ in $K[x]$.
This condition does not suffice as we can see reading the user1551's argument with $K=GF(2)$.
On the other hand, there is a solution of the initial problem in $GF(3)$.


How can I increase the row width in zurb Foundation?

Question: I am learning Zurb foundation, and my question is that how can I increase the default width of the row in the framework.
Like a 960 grid system has 960 px. How can I increase the wish of row to maybe 1200px, so should I add a custom stylesheet?
Answer: You don't have to use !important. Just place your new CSS—say app.css—below the foundation.css and use the following:
.row {
    max-width: .px;
}

You can also use another class and add this property so that it won't conflict with the default row.
Comment: This works, but in my case it also restricted the max width of a full width row, so if you have full width rows in your layout you might want to reset .row.full-width to 100%
Answer: Better way is to go to the _settings.scss file of foundation in your project, check online if you don't have _settings.css file or if you don't know its location please. just open and find this
$row-width: rem-calc(980); //change up to what you want

and this upper value will generate row-width like below value i.e 61.25rem.
/* line 228, ../../bower_components/foundation/scss/foundation/components/_grid.scss */
.row {
  margin: 0 auto;
  max-width: 61.25rem;
  width: 100%;
}

but now if you change that row-width from 980 to something like 1280, like below example
$row-width: rem-calc(1280);

then you can see below that my css is generated automatically with the new max-width
/* line 228, ../../bower_components/foundation/scss/foundation/components/_grid.scss */
.row {
  margin: 0 auto;
  max-width: 80rem;
  width: 100%;
}

be careful with that settings because you can change the look and layout of whole website drastically.
Answer: Override the max-width property of your .row class, and set it to the width you want.
.row {
    max-width: ...px !important;
}

If you'r using SASS, search for grid variables in the documentation, where you'll find info on how to override row width, gutter width and more.
$row-width: em-calc(1000);

Comment: Better never use `!important` and learn about CSS specificity. Smashing mag has a brilliant article about it http://coding.smashingmagazine.com/2007/07/27/css-specificity-things-you-should-know/
Comment: True, you can always override it by including the .row{} after the Foundation css styles - and thus omitting the !important. Or just use SASS. :) PS. even ZURB uses alot of !important; in their framework - so it can be useful in certain cases.
Answer: Foundation 6 introduces the class .expanded to make the width fluid: http://foundation.zurb.com/sites/docs/grid.html#fluid-row
It still results in problems with the padding though, no idea how to fix this.


Redirect link with query string, but only from specific page

Question: My problem is about that I want to redirect links that contains specific phrase and specific query string after question mark.
For example - redirect from:
http://example.com/first-category?p=1

to:
http://example.com/second-category

I have code in .htaccess, that redirects all links that contains p=1 after question mark:
RewriteCond %{QUERY_STRING} p=1 [NC]
RewriteRule .* http://example.com/second-category? [R=301,L]

But as I said - ?p=1 exists in links of a lot of pages (categories, manufacturers, blog info-pages etc.) and this code above would redirect my all pages with ?p=1 to /second-category, what is incorrect.
I need to define another condition (that points containing first-category phrase BEFORE question mark), but this code is not working correctly:
RewriteCond %{REQUEST_URI} first-category
RewriteCond %{QUERY_STRING} p=1 [NC]
RewriteRule .* http://example.com/second-category? [R=301,L]

Any ideas how to fix it? I am not sure what is incorrect here.
Answer:
RewriteCond %{REQUEST_URI} first-category
RewriteCond %{QUERY_STRING} p=1 [NC]
RewriteRule .* http://example.com/second-category? [R=301,L]

This should "work", so it is likely you have a caching issue. The earlier 301 (permanent) redirect that redirected everything based on the query string only will have been cached by the browser.
However, you don't need another condition. The first argument to the RewriteRule directive (ie. the pattern) already matches the URL-path. In this example, .* matches everything, so you need to make this more restrictive.
Also note that these arguments are regular expressions, so p=1 matches "p=1" anywhere in the query string, not just at the start, as in your example. Likewise, first-category would match "first-category" anywhere in the URL-path, not just at the start, as in your example.
Try the following instead:
RewriteCond %{QUERY_STRING} ^p=1$
RewriteRule ^first-category$ http://example.com/second-category? [R=301,L]

This matches exactly the request /first-category?p=1 (case-sensitive). Note that the slash prefix on the RewriteRule pattern is omitted in a directory context.
The NC flag on the condition is not required, unless you explicitly need to match P=1 as well.
If you are on Apache 2.4+ then you can use the QSD (Query String Discard) flag instead of appending a lone ? to the end of the substitution string, in order to prevent the query string from the request being implicitly copied to the substitution.
You will need to clear your browser cache before testing. It is recommended to test with 302 (temporary) redirects to avoid caching issues.
Comment: Thanks, that is totaly comprehensive answer!


Question on the property of algebraic number

Question: Given $x$ an algebraic number of degree 2. Anyone help me to prove
$$ |\sin(n\pi x)| \geq \frac{\mathrm{const.}}{n} $$ for all $n$ ?
Comment: $const = 0$ ? :-P
Answer: We denote $d(y, A) = \inf \{\mid a - y \mid,\ a \in A \}$. If you consider $x$ an algebraic number of degree $2$, then there exists $C>0$ s.t. $\forall (p,q) \in \mathbb{Z}\times \mathbb{N}^*, \mid x - \frac{p}{q} \mid \ge \frac{C}{q^2}$
Hence $$\forall n \in \mathbb{N}^*,\ d(nx,\ \mathbb{Z}) \ge \frac{C}{n}$$
Thus $d(n\pi x, \pi \mathbb{Z}) \ge \frac{\pi C}{n}$ $(*)$.
Finally, you can use that for $h \in [-\frac{\pi}{2},\frac{\pi}{2}],\ \mid \sin (h) \mid \ge \frac{1}{2} \mid h\mid$ and $\mid \sin (\pi + h) \mid \ge \frac{1}{2} \mid h \mid$.
Therefore, $$\mid \sin (n \pi x) \mid \ge \frac{1}{2} \frac{\pi C}{n}$$ (simply write $x = k\pi + h$ with $k \in \mathbb{Z}$ and $h \in [-\frac{\pi}{2},\frac{\pi}{2}]$, and $(*)$ gives $\mid h \mid \ge \frac{\pi C}{n}$).
We take $A = \frac{\pi C}{2}$, and we have, for all $n$, $\mid \sin (n\pi x) \mid \ge \frac{A}{n}$.


Is Playing Classical Guitar with Fingers PI a Bad Habit?

Question: I see most classical/flamenco guitar players use fingers IM instead (rest stroke or picado). Coming from an electric guitar background, I find the rest stroke technique extremely uncomfortable.
Is it possible to achieve great speed playing with thumb/index instead of index/middle (rest stroke)?
Are there any examples in acoustic guitar?
Comment: Why do you refer to rest stroke? IM(A) are also used in free stroke, not specifically in rest stroke. Perhaps it helps to indicate what (part of a) piece(s) you're thinking of or are trying to play.
Comment: Since the thumb is often used for "bass" accompaniment, while at the same time I and/or M are used, I'm not sure how you would want to use PI instead of IM.
Answer: The rest stroke has nothing to do with thumb or any fingers any more than free stroke, so is irrelevant. But - it's much more difficult to achieve, especially for beginners, so isn't so commonly used.
If the thumb made for faster, better playing, players would be using it more. Fingers actually are better for this - all in the same plane, and physically more similar than the thumb.
Thumb, in classical playing, being more fleshy, produces a softer sound, and thus is often used for the accompanying bass line or arpeggiated chords, usually on the lower strings.
Having said all that, using apoyando, or rest stroke, surely won't work on fast passages, as there's literally no time to rest. So, do away with that for now, try to use much less thumb - that'll set you up for later stuff - and get used to using at least I and M, and certainly introduce A into the party. It might just help to consider the classical guitar as different in many aspects from the electric, and indeed, the acoustic guitar. As one probably would considering a bass guitar, for example.
Comment: I was taught to use rest strokes for fast passages and indeed my rest strokes are faster than my free strokes. I imagine this comes down to personal preference and how one practices.
Comment: It does a bit, @bfootdav, however it is fastest to have your fingers free, for fairly obvious reasons.
Comment: What are those obvious reasons? As explained to me with a rest stroke you make one movement to pluck (your finger is then stopped by the next string) and then a second to pluck again. Two moments of effort. With a free stroke you pluck, have to stop the motion of your finger and then pluck again. The idea being that less energy is expended with a rest stroke allowing for faster playing.

In the end I don't know if/how such a thing could be measured. A brief search on the internet shows the split in opinion exists.


How to have View output is same as node output

Question: I have a content type called poem and a View page that has path like poem/% too. There is a View page for listing the poems called /poems. The poems page will list all the poem titles linked the actual poem
   (eg: "a href="poem/1">What a world ).
I have a block in the poem view to show all the poems written by the poet.
My problem here is when I go to the node by /node/1, I can see the block that list all the poems written by the poet who wrote the node/1 but when I go like /poem/1 I am not seeing the block that list the poems. The node/1 view has bold header of the title but that's missing in my /poem/1 too.
Please help me how to make poem/1 to have the same view as the /node/1.
/poems -> this will list all the poem titles in site, title link would be
/poem/1 instead of node/1
/poem/1 -> display poem content + it should display all the titles of the poem written by the author (/poem/1)
poem list view

poem view
node view of the same poem

poem view setup
Comment: It seems to be clear but not for me. :) It's confusing..poem, poem view, poem block. It seems there is something missing in views block. If possible try to make it simple or elaborate.
Answer:
but when I go like /poem/1 I am not seeing the block that list the poems. The node/1 view has bold header of the title but that's missing in my /poem/1 too.

In the Blocks Admin UI at admin/structure/blocks be sure the Block for your block view for a poem listing is enabled for the url path = poem/*.
You can also assign blocks to regions easily with the Context module.
Comment: Thanks for your answer but it's not working yet. There is no restriction on the block view. I am going to attach some screenshots.
Comment: What I said is not a configuration value in the Views UI. It is in the Blocks UI in `admin/structure/blocks`
Comment: It's enabled and the region is secondary. I am not sure how to enable for the speicfic path. I don't have any restrictions in block visibility settings. Please let me know if that's wrong.
Comment: The contextual filter setup was wrong - I set to raw and it's working fine now. Thanks for your time.


Why is the percolation threshold not well-defined in a finite lattice?

Question: I am not a mathematician but I want to get some familiarity with percolation theory for an application to my job. I am reading this text, where it is implied on page 5 that the percolation threshold is not well-defined for finite lattices.
For a 2D lattice I can imagine the percolation threshold (i.e. density where the chance you connect top to bottom of your grid becomes 1) equals the total number of points on your grid minus one row divided by the total number of points on your grid image? Adding one more point then has to connect the two halves and the row is the minimal distance to separate the two halves.
I hope someone can help me understand this better, thank you.
Best regards
Jan
Answer: Percolation theory is mainly concerned with typical phenomena of percolation processes.
Because for finite graphs the expected size of percolated clusters is a continuous function of the occupation probability.
Discontinuity emerges only when the system size becomes infinite.
In literature about percolation processes, 'percolation threshold' is used to refer to the the critical probability $p_\textrm{c}$.
Above $p_\textrm{c}$ there is percolation whereas below $p_\textrm{c}$ there is no percolation (where 'no percolation' means the the probability of such event is zero).
As for your example, the argument similar in spirit could be used to estimate the upper bound of percolation threshold.
But typically a subgraph produced by a percolation process (e.g., bond/site percolation) would be far different from your example.


How to style a label with a colon

Question: I have a details view window in WPF and a label may look like this.

So that is obtains it content from my property Resource.
How can transform/format the content so it has a colon after each label item.  e.g. instead of the content simply displaying Reference I want it to transform to Reference:
Answer: The solution I ended up with was:

Comment: Strangely enough - this was one of the earlier solutions I tried and it would not work?  I have since discovered that sometimes the 'wysiwyg' window does not update correctly until I do a full compile !
Comment: same thing here in VS2017 Pro
Answer: You can use a Binding with StringFormat to format the result.
<Label Content="{Binding Source={x:Static properties:Resource.Reference}, StringFormat='{}{0}:'}"

Note that the {} before the format string is here to prevent the XAML parser from treating {0} as a markup extension, like {StaticResource} for example.
Comment: Thank-you for your response.  For some strange reason I could not get your suggestion to work, but it did set me on the right course to a solution which was:  Content="{x:Static properties:Resources.Date}" ContentStringFormat="{}{0}:"

How to style a label with a colon


Geometric morphisms between presheaves

Question: I've read that every functor, $f:C \to D$, generates a geometric morphism from $f^* \vdash f_*:Sets^{C^{Op}} \to Sets^{D^{Op}}$.
But I don't have a feel for how this really works in concrete examples. Take for example the inclusion function between the discrete two element category $|2|$, and the partial order $2 := (\{0,1\}, \leq)$. The induced functor from $Sets^{|2|} \to Sets^2$ associates each pair of sets with a pair of sets and a function between them. But I can't think of any natural functor that would come up with a function between sets out of thin air like this. It would be helpful to me if I could see this functor described concretely.
Answer: The general way to calculate the functor $\mathbf{Set}^{C^{op}}\to \mathbf{Set}^{D^{op}}$ is to consider the left Kan extension of a functor $F:C^{op}\to \mathbf{Set}$ along the functor $f^{op}:C^{op}\to D^{op}$. Since $C,D$ are presumably small and $\mathbf{Set}$ is co-complete, such a Kan extension will always exist. The easiest way to calculate it is, for each $d$ in $D$, we take $Lan_{f^{op}} F(d)$ to be the colimit of $F\circ Q:(f^{op}\downarrow d)$ in $\mathbf{Set}$. It will turn out that the existence of $Lan_{f^{op}} F$ for any $F$ is the same as there being a left adjoint to $-\circ f:\mathbf{Set}^{D^{op}}\to \mathbf{Set}^{C^{op}}$.
Understanding what this means in the case of a given poset $P$ is a little harder to visualize. For a functor $G$ on $|P|$ and an element $p$ of the poset, it takes that $p$ to the coproduct $G^*p:=\coprod\{G(q)|q\geq p\}$, and for the inequality $p<p'$, we have the coproduct inclusion of $G^*p'$ into $G^*p$.
(Hopefully I got all this the right way around. I sometimes get right and left Kan extensions flipped.)
Comment: I stumbled across this again and realized I had ignored the part of the question where the point was about understanding the direct image part of a geometric morphism and I wrote out the wrong adjoint! Instead you want to use the dual construction and take $p$ to the *limit* of $G\circ Q:(d\downarrow f^{op})\to\mathbf{Set}$, where $f:|P|\to P$ is the inclusion of the elements of the poset. It's a pretty straightforward dualization of the one I described above.
Answer: The induced functor sends a pair of sets $A,B$ to the arrow $i_A:A\to A\sqcup B$. Its right adjoint sends an arrow to its domain and codomain. This actually has a further right adjoint, $A,B\mapsto (p_B: A\times B\to B)$.
Comment: There is a formula for the left Kan extension, which is what this is, and which you can look up: you calculate a colimit over a certain comma category. In small cases like this, you can also work things out for yourself using the adjunction isomorphisms, since you know how to compute the right adjoint. Try the first four the inclusion of either point into the arrow, for instance.
Comment: Thank you! Is there simple way to see how that generalizes to an arbitrary poset, $P$, and the corresponding discrete category $|P|$?

Geometric morphisms between presheaves


Do people in Australia use the German notation?

Question: One of my cousins live in Australia and whenever she writes down musical notes, she uses the German notation instead of the standard English.  For example, instead of using ♭ (C♭, D♭, E♭, F♭, G♭, A♭, B♭) , she writes "es" (Ces, Des, Es, Fes, Ges, As, B) .  She will also write the keys in German (ex. "fis-moll" for f♯-minor) .  When I asked her why she writes them that way, she answered that she was instructed by someone who uses the German notation.

So the question is: Do people in Australia use the German notation?
Comment: Mind that they are multiculti. I have a facebook-friend in australia the "yodelling maria" from AUSTRIA. She seems not to be the only one beside the English migrated. The english surely are using ♭. (I've copied ♭ from your question, how can I type it with my keyboard of win 10? I know it was explained in the meta, but I didn't understand the codes ...)
Comment: Well, the THING is, sometimes when she uses the German notation, it really confuses me.  Especially, the "B♭-B" and "B-H" is ***EXTREMELY*** confusing!
Comment: and what do you think it is for all german, that all the english american use the B insted of the H? :)  The mass of Bach is called H-moll Messe. What it is in English? B-minor. But I explained to my pupils at school (from 9 to 17 years) it would be more logical to use the English spelling but there are still other points where you have to be flexilby thinking in music.
Answer: The German notation is not in common usage in Australia.
Source: Am Australian.
There's a lot of German influence in South Australia (the state) particularly. So there's potential for some people to use it. However, even in South Australia, I've never heard it. The average musician here tends to use a mix of British and American conventions.
Comment: @MaikaSakuranomiya Nah, Sydney is about 1400km away from South Australia. That being said, there are plenty of German people in Syndey too. The influence is just more prevalent in South Australia.
Comment: Nice!  Is Sydney in South Australia?  Because my cousin lives in Sydney.
Answer: The "German" notation is a notation applied in several European countries. We use it in Denmark. In this system B is called H and B♭ is called B. This means that you get the idea in compositions that applies the 4 notes B-A-C-H. Several composers use that sequense of notes in a composition inclusive Bach himself.
Anyway, the normal notation in Australia is the same as in other English speaking countries. I know that from an Australian musician.
Answer: Seems you've answered your own question:  the cousin in question uses the German notation.  Extrapolation to the population from a single instance is bad mathematics :-) .  What this means is this:  you know for sure that there is one person in Australia who uses German notation.  You know nothing about the rest of the population.  However, that is true ("know nothing") for the entire population of China, or Japan, or  Paraguay.  As such, your question has no functional value - it's got nothing to do with Australia per se .  There is no reason to expect any country, with the faintly possible exception of Germany, has a significant number of musicians who work with German notation.
commentary
At some point, every musician (at least in the classical world) has to learn not only the standard Italian but also German and French notation (the latter being mostly the associated terminologies), how to read those crazy French scores where the eighth-rest symbols are backwards, and so on.  It's the music-world equivalent of the (thousands of) different spoken languages and text characters used around the world.
Comment: @CarlWitthoft The OP didn't make any claim though, they just asked a question. They didn't make an a priori assumption, instead they offered evidence (in the form of a cousin). You're the one making the a priori assumption - you don't know if there are people in Australia who use German notation, you're just assuming there aren't.
Comment: This does not answer my question.  Sorry.
Comment: This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - [From Review](/review/low-quality-posts/47109)
Comment: This response really doesn't make sense. First you say that the OP answered their own question by demonstrating that one Australian uses German notation, then you say that we need a larger sample size to know the answer... Why respond if you don't know the answer the question?
Comment: @CarlWitthoft I mean that you're contradicting yourself. You admit that we know of one person in Australia who uses this notation, then you say "There is no reason to expect any country ... has a significant number of musicians who work with German notation." Do you have any evidence about the second part, or are you just guessing?
Comment: @Peter  I'm simply saying that when someone makes a claim, it is up to them to generate supporting evidence.  I'm pointing out that we have no *a priori* reason to expect Australia or any other country to be primarily German-style.
Comment: @user45266 fine; I'll expand on the mathematics of the situation.
Comment: @Peter you are not making sense.  What do you mean?


If $f(t) = 1+ \frac{1}{2} +\frac{1}{3}+....+\frac{1}{t}$, find $\sum^n_{r=1} (2r+1)f(r)$ in terms of $f(n)$

Question: If $f(t) = 1+ \frac{1}{2} +\frac{1}{3}+....+\frac{1}{t}$,
Find $x$ and $y$ such that $\sum^n_{r=1} (2r+1)f(r) =xf(r) -y$
Comment: Firstly, $f()$ isn't a polynomial; it's not even a rational function of $t$, since its denominator grows faster than any power of $t$ does (it's $LCM(1\ldots t)$, which grows similarly to $t!$).  Secondly, it's not entirely clear what's being asked; are you supposed to find $x$ and $y$ in the given expression?
Comment: I think  $LCM(1…t) \approx e^t$ (from the prime number theorem).
Comment: I've edited the question to reflect what I presume the actual problem is.  Sultan, if this is wrong, please let me know and feel free to further edit to express the real question.
Comment: $xf(r) -y$ or $xf(n) -y$?
Answer: I'm presuming that the problem asks you to find $x$ and $y$ to make the stated equation true.  If that's so, then you should be able to use the concept of summation by parts (which is the discrete equivalent of integration by parts) to solve the problem; choosing $f_k=\sum_{i=1}^k\frac1i$ and $\Delta g_k=2k+1$, then you should be able to find simple closed forms both for $\Delta f_k$ and for the $g_k$ (hint: $g_{k+1} = \Delta g_k+g_k = g_k+(2k+1)$ ) and thus use the summation by parts formula to express your sum in terms of $f(n)$.
Answer: Since $(n+1)^2 - n^2 = 2n+1$, we'd expect $\sum_{r=1}^n (2r+1)f(r)$ to be something like $n^2 f(n)$. A little experimentation shows that it's actually $(n+1)^2 f(n) - n(n+1)/2$. $\textbf{Proof}$: At $n=1$, this is $4 - 1 = 3 = (2+1)f(1)$.
The forward difference of $(n+1)^2 f(n) - n(n+1)/2$ is $(n+2)^2 f(n+1) - (n+1)(n+2)/2 - [(n+1)^2 f(n) - n(n+1)/2]
= (n+2)^2 f(n+1) - (n+1)^2 (f(n+1)-1/(n+1)) - (n+1)
= (2n+3)f(n+1) = (2(n+1)+1)f(n+1)$,
as required.


R classifier that handles NA's at prediction time

Question: Are there any high performing classifiers implemented in R capable of handling NA's at prediction time? By high performing I mean models that in general produce good results (random forest, SVM, Boosting, etc.). Currently, I was trying with randomForest package but when trying to predict an observation having in some of its columns NA's then, the result is just NA.
At training time I have no problem since I can guarantee that the training data will not have any NA's. For my use case imputation is not an option, so I am looking for a classifier that just can handle NA values (maybe by ignoring them) at prediction time. Note: my predictor variables are numeric and categorical.
Answer: Gradient boosted trees handle missings.
The popular implementations in R, xgboost and gbm, both create a missing node alongside the left and right nodes for each split. If there are no missing elements in the training data then the missing node prediction is the same as the root prediction$^1$. Otherwise the prediction for the missing node is learned.
Be very careful though, as it sounds like your training data and implementation data are very different. If the model expects to always be able to see a certain powerful predictor, don't expect good performance when that predictor is later masked. Consider if there is a way to make your training data look more like the data on which you want to implement your model. Boosted trees' handling of missing is a neat convenience when your training and scoring data both have equally distributed missings, but it is not a catch-all for what you are trying to do.
$^1$ Edit: apparently xgboost always sends missings to the right node if it does not encounter any in training, and fits them to the left or right node otherwise. It does not spawn third node.
Answer: I have done some comparison with the other methods and XGboost handle missing data better. data are not presented in the feature matrix treated as "missing" and for continuous feature, it learns the best direction to go when the value is missing.
You can read more here


Field Collections not displaying in Content Template

Question: I'm using Content Templates (Contemplate) module to style a node display for a content type that uses Field Collections. When I view the node's display page before changing anything in the Content Template, the Field Collections display fine. As soon as I tick the "Affect body output" checkbox to adjust the template, the Field Collection content no longer shows up on the display. The header is there, but the content is gone.
How can I get the Field Collection content to display? Is there an incompatibility issue with Content Templates and Field Collections?
This is a Drupal 7 site... and, before you ask, I need to use Content Templates for theming due to a somewhat locked down development environment.
Answer: Not necessarily an answer, but a viable workaround:
The Field Collection content is available to views, so I made a view block that prints out the Field Collection content where the contextual relationship is the node's NID. That block gets displayed on this content type only. With some Javascript trickery, I'll be able to position it where it needs to go.
I'm open to a real answer, but for now, this is all I've got.


Validation tool for recommendation system

Question: I have developed a recommendation system which recommends the products based on the transaction history of the customer. All I have is one year of transaction data with no information on purchase reasons like due to recommendation system or email campaign etc.
I need to validate my results before pushing it to production. Is there any method to do this?
Thanks
Comment: Why can't you use the traditional training/test split?
Comment: I don't have data for any previous recommendation campaign. How I can test ? What could be my performance measure
Comment: Have you used K-folds ?
Answer: Unfortunately, you may not be able to validate your model correctly at all before going into production without having additional data.  It sounds like you used all the available data to build the model for your recommendation system.  This is not the way to approach the predictive model building process.  For future reference, at the very least what you should have done is split your data into two parts:

One part for training your model--perhaps 80% of the data could have been reserved for this; and
The other 20% should have been set aside for validation.

To be very thorough you could have split your data into 3 chunks and reserved your last chunk of data for validation of your final model prior to deployment to production.
Why not validate against the data you have?
You might ask yourself why you can't simply validate the data with the data you used to build the model?  Well, that's because you may have "overfit" your model to the particular features of the dataset--and not necessarily to the general features that drive purchases.  So, had you set aside 20% of your data before you built your model, then once you found a few candidate models for your recommendation system, then you could have validated each one of those models against your "hold-out" or validation dataset.  You'd then want to select the one that had the least error, or the one that led to the greatest proportion of recommended items that were purchased (or greatest recommended profit, etc.).
What to do now?
Given that you've already built the recommendation system with all your data and you no longer have any data for validation, I believe your only choice now is to deploy your solution to production, but randomly select customers that will receive recommendations from your system.  You will then have some data that you can use to compare profits, purchases, etc. from those who received recommendations from your model versus those who did not receive recommendations from your model.  There are a few different sampling schemes you can use for this purpose, so you should research those.  You might also want to review articles like this to determine how you might want to go about validating in production.
Best of luck with your new system!
Answer: Check how well your clusters (bad vs. good recommendations) are separated. Various distance metrics are available for such comparisons. See also my article on the elbow rule at https://dsc.news/2EYkh3E. The strength of the signal is an indicator of how well your classes are separated. Try different models, select the one with the best discriminating power.


Pegar nome do arquivo que não possui extensão usando foreach (glob())

Question: Como pegar apenas arquivos sem extensão?
exemplos
1bdfe4baf9061c3667ded70d8f66142c
2a0daf2d8d5b7ea1813c7a84b146d092
91e3b288eab8d59598a52221296f8995
 $f=glob("*");
 foreach ($f as $arquivo) {
 echo "$arquivo
";
 }
 //Neste caso esta exibindo todos arquivos

Answer: Você pode usar:

strpos para encontrar se o nome tem ponto (.)
array_filter para filtrar o array antes de iterar no foreach
basename para pegar somente o nome do arquivo

Ficaria algo como:
<?php

$arquivos = array_filter(glob('*'), function ($path) {
    return strpos(basename($path), '.') === false;
});

foreach ($arquivos as $arquivo) {
    echo "$arquivo
";
}

Entendi errado, removi esta parte:
Pode usar o pathinfo assim:
<?php

$arquivos = glob("*");

foreach ($arquivos as $arquivo) {
    $arquivo = pathinfo($arquivo, PATHINFO_FILENAME);

    echo "$arquivo
";
}


Multiple Servers for Single Domain

Question: I need help in determining if this use case is possible:

We have one primary mail server where we want certain email addresses to be stored from domainA.com
All of the rest of the email addresses not defined on primary mail server, we want to be forwarded to a secondary server using secondary MX records (for same domainA.com)

Example: we have a domain which has several business email addresses (employees, sales, support, etc.) but on same domain we also have thousands of 'virtual' emails that we parse for our application. (we don't care about POP3 access etc. for the virtual addresses).
There is a service we are trying to use that can do all of the email parsing for us, but requires us to point our MX records to their server.
We want to be able to control our business emails on our own server, and only send the virtual emails to them.
Any suggestions, on how we can achieve this?
Comment: It would help if you tell us what email servers you are using.
Comment: Secondary MX records are for redundancy not routing purposes
Answer: Short of using a different domain name you are going to struggle.
Email works something like this (feel free to correct my mistakes):

The sending Email client performs a DNS lookup on the domain part of the email address (everything to the right of the @).
It will either get the IP address from a MX record, if there isn't one it just goes for the A record
The email client opens a SMTP connection to the IP address it found in 2. and tries to  deliver the email.
The receiving server looks at the email address, it checks that it is accepting email for that domain and it may check if the account exist before accepting otherwise it just accepts the email.
Only now is any routing done on the 'name' part of the email address (everything to the left of the @).  The server then handles it according to whatever rules it has.

Consequently you can't use DNS and hence MX records to route email according to the 'name' part of the email address.

To potentially solve your problem - I don't see why your 'service' needs the MX record pointed at it (of course you may want a reverse DNS lookup or PTR record for SPAM purposes).  Just set your MX record to point to a mail server you control and get it to forward on all of your 'virtual' email address to your service - it shouldn't care that they come from you and not the original sender.
Or change your staff email address to a different domain or subdoamin perhaps firstname.lastname@example.com?

Multiple Servers for Single Domain


Definir tamanho de tabela responsiva

Question: Estou criando uma tabela responsiva, só que quando estou numa tela grande, a tabela fica menor do que devia, tentei adicionar um max-width no css dela, só que mesmo assim não fica do tamanho proposto.

                    Código
                    Descrição
                    Categoria

                    001
                    Notebook i7 8GB Branco
                    Informática

                    002
                    Caneta Esferográfica Azul
                    Papelaria

Answer: A sintaxe está errada.
Falou declarar o class .

Definir tamanho de tabela responsiva


Is introducing a try-catch block in JavaScript considered bad with respect to performance?

Question:
Possible Duplicate:
Javascript Try-Catch Performance Vs. Error Checking Code

A colleague of mine told me that using a lot of try catch blocks in javascript is going to be a hit in performance . Is that claim true and if yes then why  ?
Comment: Have a look at http://stackoverflow.com/questions/3217294/javascript-try-catch-performance-vs-error-checking-code
Comment: @Geek I like your rating, Don't change it a bit!
Comment: @BillyMoon I'm forced to down vote ...
Answer: Short answer, yes he is correct. A try/catch statement has do to certain things under the hood in order to work. For instance, it will extend the scope lookup chain (which might not be that big problem in modern environments) but it especially needs to evaluate whatever code is within that try-block, to figure if there are any errors thrown.
Anyway, try/catch blocks are a great opportunity to make your code stable. However, you should always apply it on the smallest fraction of your code possible and of course only, if it is really needed (like, avoiding browser specific bugs/errors which you can't work around). Just putting like all of your script into one big try/catch block, is certainly the worst idea.
Comment: What do you mean by "*especially needs to evaluate the code within the `try`-block*" - wouldn't one need to do that anyway, without try-catch?
Answer: Yes. There is a good article on that at dev.opera.com.
This is likely because try-catch-blocks have that certain, unusual handling of result objects, they need to check whether its type is throw. And then, executing the catch block is not as easy as it looks in the code. See Ecmascript §12.14: The try Statement for further reading.
Still, try-catch-clauses are a powerful feature, and one should use them where appropriate and useful. But instead of having them inside performance-critical functions, you should wrap them around so they are not executed too often.


Solving simultaneous equation involving quadratic and exponential

Question: I have two equations $y=x^2$ and $y=e^{x+1}$. I want to solve them simultaneously and find $x.$ But I am having trouble solving them. I have tried the following:
\begin{aligned}x^2&=e^{x+1}\\
\ln(x^2)&=x+1\\
2\ln(x)&=x+1\\
\ln(x)&=\frac{x+1}{2}
\end{aligned}
and then I have no more ideas.
Comment: You have an obvious solution, which is $x=-1$ . Studying variations of the function $x\mapsto e^{x+1}-x^2$ might give you that this is the unique solution (i've not checked)
Comment: It is $$x=-1$$ or $$x=-2 W\left(-\frac{\sqrt{e}}{2}\right)$$
Comment: With the LambertW function.
Comment: @Dr.SonnhardGraubner so there is no way of solving this algebraically? I will just have to see that there is a obvious solution $x=-1$?
Comment: I think there is no way, but $x=-1$ is algebraically solution, the other solution not.
Answer: For $x\le0$, the function $x^2$ is strictly decreasing, and the function $e^{x+1}$ is strictly increasing, so there is at most one solution. By inspection $x=-1$ is a solution, so there are no others for $x<0$.
For $x>0$ we want to show that $$e^{x+1}>x^2\quad(*)$$ so that there are no solutions for $x>0$. That would be easy with calculus, but the OP has classified it as precalculus, so we have to work a little harder.
Note first that $(x-1)^2>2$ for $x\ge3$, so (rearranging) $2x^2>(x+1)^2$. We claim that for any positive integer $n>3$ we have $2^n\ge n^2$. It is true for $n=4$. Assume it is true for $n$, then $2^{n+1}=2\cdot2^n\ge2n^2>(n+1)^2$, so it is true for $n+1$ and hence for all $n$.
Now consider $4\le n<x<n+1$. We have $e^{x+1}>2^{x+1}\ge2^{n+1}\ge (n+1)^2\ge x^2$. So we have established (*) for $x\ge4$.
$(*)$ is obviously true for $0\le x\le 1$. It is true for $1\le x\le2$ because $e^{x+1}>2^{1+1}=4\ge x^2$. It is true for $2\le x\le 4$ because $e^{x+1}>2.7^3>16\ge x^2$.


How to put a hyperlink into an MMS message?

Question: What language is used to insert hyperlinks into an MMS message?
I'm sending MMS messages to my cellphone, from my computer, but don't know how to include a link.
I'm using php to send emails to the MMS service.  Images and plain text show up just fine.
Comment: Possible duplicate of:  http://stackoverflow.com/questions/368348/internal-hyperlinks-in-a-mms
Comment: Off topic: what MMS service do you use?
Answer: You should probably just include the link in plaintext.  However, there is another way detailed here:
http://discussion.forum.nokia.com/forum/showthread.php?193656-Invoking-Browser-from-MMS


Pegar o valor de nome e da data (usando datepicker), e depois calcular utilizando somente (JQUERY),

Question:

 $(function () {

                $("#datepicker").datepicker({

                });

            });

        <form id="formu">
            Nome:
            <input type="text" id="name">

            Data de nascimento:
            <input type="text" id="datepicker" name="data"/>

            <input type="button" id="botton" value="Ok">
        </form>

** a idade do usuario. Em seguida mostrar na div resultado.**
Answer:

var esteAno = new Date().getFullYear();
$('#datepicker').datepicker({
  dateFormat: 'dd-mm-yy',
  onSelect: function(date) {
    var ano = date.split('-')[2]; // ano aqui
    var anos = esteAno - ano;
    $('#resultado').html('');
    var strAnos = 'anos';
    if(anos === 1) {
        strAnos = 'ano';
    }
    $('#resultado').html($('#name').val() +' você tem ' +anos+ ' ' +strAnos);
  }
});
<link href="https://code.jquery.com/ui/1.11.4/themes/pepper-grinder/jquery-ui.css" rel="stylesheet"/>

<form id="formu">
        Nome:
        <input type="text" id="name">

        Data de nascimento:
        <input type="text" id="datepicker" name="data"/>

        <input type="button" id="botton" value="Ok">
    </form>

Comment: So uma duvida `onSelect: function(date) { `  é para executar esta função a partir do momento que o usuário selecionar a data isto?
Comment: Yap, a partir do momento em que clica/pressiona uma data @user49744
Comment: Para que significa nesta parte do codigo:    `date.split('-')[2];`    ?
Comment: Dividimos a data pelo '-' e vamos buscar o ultimo do conjunto (array) @user49744.
Comment: E porque vc colocou  `$('#resultado').html('');` ?
Comment: Para inserir na div `#resultado`


How to tranfer image to other activity using bundle Android Studio

Question: Here I want to ask how to send data retrieved from the database from the RecyclerViewAdapter to another activity (UpdateActivity).
This is my RecyclerViewAdapter which will send the image

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DecodeFormat;
import com.bumptech.glide.request.BaseRequestOptions;
import com.bumptech.glide.request.RequestOptions;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>{

    private ArrayList<data_mahasiswa> listMahasiswa;

    private Context context;

    //    Interface delete data
    public interface dataLinstener{
        void onDeleteData(data_mahasiswa data, int position);
    }

    dataLinstener linstener;

    //    konstruktor input data
    public RecyclerViewAdapter(ArrayList<data_mahasiswa> listMahasiswa, Context context) {
        this.listMahasiswa = listMahasiswa;
        this.context = context;
//        delete fungsi listener
        linstener = (ListData)context;
    }

    @NonNull
    @Override
    public RecyclerViewAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.view_design, parent,false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerViewAdapter.ViewHolder holder, int position) {

        //        Mengambil Nilai/Value yang terdapat pada rcview berdasarkan posisi
        final String gambar = listMahasiswa.get(position).getGambar();

        final String NIM = listMahasiswa.get(position).getNim();
        final String Nama = listMahasiswa.get(position).getNama();
        final String Fakultas = listMahasiswa.get(position).getFakultas();
        final String Prodi = listMahasiswa.get(position).getProdi();
        final String Tanggal = listMahasiswa.get(position).getTanggal_lahir();
        final String Phone = listMahasiswa.get(position).getPhone();
        final String Email = listMahasiswa.get(position).getEmail();
        final String IPK = listMahasiswa.get(position).getIpk();
        final String Alamat = listMahasiswa.get(position).getAlamat();
        final String Golongan_Darah = listMahasiswa.get(position).getGolonggan_darah();
        final String Jenis_Kelamin = listMahasiswa.get(position).getJenis_kelamin();

//        mengisi nilai

        BaseRequestOptions requestOptions = (RequestOptions) ((RequestOptions) ((RequestOptions) ((RequestOptions) ((RequestOptions) new RequestOptions().format(DecodeFormat.PREFER_ARGB_8888)).override(Integer.MIN_VALUE)).placeholder((int) R.color.purple_200)).centerCrop()).fitCenter();
        if (gambar == null) {
            holder.Gambar.setImageResource(R.drawable.ic_baseline_person_100);
            ViewHolder viewHolder = holder;
            String str = NIM;
        } else {
            Glide.with(holder.itemView.getContext()).load(gambar.toString().trim()).apply(requestOptions).into(holder.Gambar);
        }

        holder.NIM.setText("NIM \t\t\t\t: " + NIM);
        holder.Nama.setText("Nama \t\t\t: " + Nama);
        holder.Fakultas.setText("Fakultas \t\t: " + Fakultas);
        holder.Prodi.setText("Prodi \t\t\t: " + Prodi);
        holder.Tanggal.setText("Tanggal \t\t: " + Tanggal);
        holder.Phone.setText("No Phone \t: " + Phone);
        holder.Email.setText("Email \t\t\t: " + Email);
        holder.IPK.setText("IPK \t\t\t\t: " + IPK);
        holder.Alamat.setText("Alamat \t\t: " + Alamat);
        holder.Golongan_Darah.setText("Golongan Darah \t\t: " + Golongan_Darah);
        holder.Jenis_Kelamin.setText("Jenis Kelamin \t\t\t: " + Jenis_Kelamin);

        holder.ListItem.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                final String[] action = {"Update","Delete"};
                AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
                builder.setItems(action, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which){
                            case 0:
//                        aktivity update / fungsi update
                                Bundle bundle = new Bundle();
                                bundle.putString("dataNIM", listMahasiswa.get(position).getNim());
                                bundle.putString("dataNama", listMahasiswa.get(position).getNama());
//                                Menggunakan spinner
                                bundle.putString("dataFakultas", listMahasiswa.get(position).getFakultas());
                                bundle.putString("dataProdi",listMahasiswa.get(position).getProdi());

                                bundle.putString("dataTanggal", listMahasiswa.get(position).getTanggal_lahir());
                                bundle.putString("dataPhone",listMahasiswa.get(position).getPhone());
                                bundle.putString("dataEmail",listMahasiswa.get(position).getEmail());
                                bundle.putString("dataIPK",listMahasiswa.get(position).getIpk());
                                bundle.putString("dataAlamat",listMahasiswa.get(position).getAlamat());
//                        kurang golongan darah dan gender / menggunakan radio
                                bundle.putString("dataGolongan_Darah",listMahasiswa.get(position).getGolonggan_darah());
                                bundle.putString("dataJenis_Kelamin",listMahasiswa.get(position).getJenis_kelamin());
//                        gambar
                                **bundle.putString("dataGambar",listMahasiswa.get(position).getGambar());**
//                        primary key
                                bundle.putString("getPrimaryKey",listMahasiswa.get(position).getKey());
                                Intent intent = new Intent(v.getContext(), UpdateActivity.class);
                                intent.putExtras(bundle);
                                context.startActivity(intent);

                                break;
                            case 1:
                                linstener.onDeleteData(listMahasiswa.get(position), position);
                                break;
                        }
                    }
                });
                builder.create();
                builder.show();
                return true;
            }
        });
    }

    @Override
    public int getItemCount() {
        return listMahasiswa.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        private TextView NIM, Nama, Fakultas, Prodi, Tanggal, Phone, Email, IPK, Alamat, Golongan_Darah, Jenis_Kelamin;
        private ImageView Gambar;

        private LinearLayout ListItem;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            Gambar = itemView.findViewById(R.id.ivGambar);

            NIM = itemView.findViewById(R.id.tvNim);
            Nama = itemView.findViewById(R.id.tvNama);
            Fakultas= itemView.findViewById(R.id.tvFakultas);
            Prodi= itemView.findViewById(R.id.tvProdi);
            Tanggal= itemView.findViewById(R.id.tvTanggal);
            Phone= itemView.findViewById(R.id.tvPhone);
            Email = itemView.findViewById(R.id.tvEmail);
            IPK= itemView.findViewById(R.id.tvIPK);
            Alamat = itemView.findViewById(R.id.tvAlamat);
            Golongan_Darah= itemView.findViewById(R.id.tvGolongan_Darah);
            Jenis_Kelamin= itemView.findViewById(R.id.tvJenis_Kelamin);
            ListItem = itemView.findViewById(R.id.list_items);

        }
    }

}

and this is the activity that will receive the image (UpdateActivity)
package com.example.presentasi;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.UUID;

import static android.text.TextUtils.isEmpty;

public class UpdateActivity extends AppCompatActivity {

    //    tambahan spinner
    private String[] ListProdi,ListFakultas;

    private Button Update;
    private EditText NIM, Nama, Phone, Email, IPK, Alamat,Tanggal;
    private Spinner Fakultas, Prodi;
    private ImageButton PilihGambar;
    private ImageView ViewGambar;
    private CheckBox gdA, gdB, gdAB, gdO;
    private RadioButton Pria, Wanita;

    private String cekNIM,cekNama,cekPhone,cekEmail,cekIPK,cekAlamat;
    private DatabaseReference getReference;

    //    tanggal
    Calendar calendar;
    DatePickerDialog datePickerDialog;

    //    image pilih
    private Bitmap bitmap;
    private Uri gambarUri;

//    Upload
    private String getNIM,getNama,getPhone,getEmail,getIPK,getAlamat,getFakultas,getProdi,getTanggal_Lahir,getGambar,getJenis_Kelamin,getGolongan_Darah;
    private StorageReference reference = FirebaseStorage.getInstance().getReference();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_update);

        getSupportActionBar().setTitle("Update Data");
//        Button
        Update = findViewById(R.id.btUpdate);
        Tanggal = findViewById(R.id.btTanggal);
//        EditText
        NIM = findViewById(R.id.etNim);
        Nama = findViewById(R.id.etNama);
        Phone = findViewById(R.id.etPhone);
        Email = findViewById(R.id.etEmail);
        IPK = findViewById(R.id.etIpk);
        Alamat = findViewById(R.id.etAlamat);
//        Spinner
        Fakultas = findViewById(R.id.spFakultas);
        Prodi= findViewById(R.id.spProdi);
//        Image
        ViewGambar = findViewById(R.id.ivGambar);
        PilihGambar = findViewById(R.id.ibGambar);
//        Checkbox
        gdA = findViewById(R.id.cbA);
        gdB = findViewById(R.id.cbB);
        gdAB = findViewById(R.id.cbAB);
        gdO = findViewById(R.id.cbO);
//        RadioButton
        Pria = findViewById(R.id.rbPria);
        Wanita= findViewById(R.id.rbWanita);

        FirebaseDatabase database = FirebaseDatabase.getInstance();
        getReference = database.getReference();
        getData();

        Update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                getNIM = NIM.getText().toString();
                getNama = Nama.getText().toString();
                getPhone = Phone.getText().toString();
                getEmail = Email.getText().toString();
                getIPK = IPK.getText().toString();
                getAlamat = Alamat.getText().toString();
                getFakultas = Fakultas.getSelectedItem().toString();
                getProdi = Prodi.getSelectedItem().toString();

                if (gdA.isChecked()){
                    getGolongan_Darah = gdA.getText().toString();
                    gdB.setChecked(false);
                    gdAB.setChecked(false);
                    gdO.setChecked(false);
                }else {
                }if(gdB.isChecked()){
                    getGolongan_Darah = gdB.getText().toString();
                    gdA.setChecked(false);
                    gdAB.setChecked(false);
                    gdO.setChecked(false);
                }else {
                }if (gdAB.isChecked()){
                    getGolongan_Darah = gdAB.getText().toString();
                    gdA.setChecked(false);
                    gdB.setChecked(false);
                    gdO.setChecked(false);
                }else {
                }if (gdO.isChecked()){
                    getGolongan_Darah = gdO.getText().toString();
                    gdA.setChecked(false);
                    gdAB.setChecked(false);
                    gdB.setChecked(false);
                }else {
                }

                if(Pria.isChecked()){
                    getJenis_Kelamin = Pria.getText().toString();
                }else {

                }if(Wanita.isChecked()){
                    getJenis_Kelamin = Wanita.getText().toString();
                }

                getTanggal_Lahir = Tanggal.getText().toString();

                Toast.makeText(UpdateActivity.this,"Upload Data",Toast.LENGTH_SHORT).show();
                checkUser();

            }

        });

        //        Date Picker
        Tanggal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                calendar = Calendar.getInstance();
                int hari = calendar.get(Calendar.DAY_OF_MONTH);
                int bulan = calendar.get(Calendar.MONTH);
                int tahun = calendar.get(Calendar.YEAR);

                datePickerDialog = new DatePickerDialog(UpdateActivity.this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                        Tanggal.setText(dayOfMonth + "/" + (month + 1) + "/" + year);
                    }
                }, hari,bulan,tahun);
                datePickerDialog.show();
            }
        });

        PilihGambar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UpdateActivity.this.getimage();
            }
        });

    }

    private void getData(){

        **int resId =  getIntent().getExtras().getInt("dataGambar");**
        **ViewGambar.setImageResource(resId); **

        final String getNIM = getIntent().getExtras().getString("dataNIM");
        final String getNama = getIntent().getExtras().getString("dataNama");

//        spinner
        final String getFakultas = getIntent().getExtras().getString("dataFakultas");
        final String getProdi = getIntent().getExtras().getString("dataProdi");

        ListFakultas = new String[]{"Ilmukomputer","Ekonomi"};
        ArrayAdapter<String> fakultasadapter = new ArrayAdapter<String>(this,R.layout.support_simple_spinner_dropdown_item,ListFakultas);
        Fakultas.setAdapter(fakultasadapter);
        Fakultas.setSelection(fakultasadapter.getPosition(getFakultas.trim()));

        ListProdi = new String[]{"Informatika","Sistem Informasi","Bisnis Digital","Teknologi Informasi"};
        ArrayAdapter<String> prodiadapter = new ArrayAdapter<String>(this,R.layout.support_simple_spinner_dropdown_item,ListProdi);
        Prodi.setAdapter(prodiadapter);
        Prodi.setSelection(prodiadapter.getPosition(getProdi.trim()));

        final String getTanggal = getIntent().getExtras().getString("dataTanggal");
        final String getPhone = getIntent().getExtras().getString("dataPhone");
        final String getEmail = getIntent().getExtras().getString("dataEmail");
        final String getIPK = getIntent().getExtras().getString("dataIPK");
        final String getAlamat = getIntent().getExtras().getString("dataAlamat");

//        mengambil data golongan dan jenis kelamin
        if ("A".equals(getIntent().getExtras().getString("dataGolongan_Darah"))){
            gdA.setChecked(true);
        }else if ("B".equals(getIntent().getExtras().getString("dataGolongan_Darah"))){
            gdB.setChecked(true);
        }else if ("AB".equals(getIntent().getExtras().getString("dataGolongan_Darah"))){
            gdAB.setChecked(true);
        }else if ("O".equals(getIntent().getExtras().getString("dataGolongan_Darah"))) {
            gdO.setChecked(true);
        }
        if ("Pria".equals(getIntent().getExtras().getString("dataJenis_Kelamin"))){
            Pria.setChecked(true);
        }else if ("Wanita".equals(getIntent().getExtras().getString("dataJenis_Kelamin"))){
            Wanita.setChecked(true);
        }

        NIM.setText(getNIM);
        Nama.setText(getNama);

        Tanggal.setText(getTanggal);
        Phone.setText(getPhone);
        Email.setText(getEmail);
        IPK.setText(getIPK);
        Alamat.setText(getAlamat);

    }

//    private void updateMahasiswa(data_mahasiswa mahasiswa){
//        String getKey = getIntent().getExtras().getString("getPrimaryKey");
//        getReference.child("Admin")
//                .child("Mahasiswa")
//                .child(getKey)
//                .setValue(mahasiswa)
//                .addOnSuccessListener(new OnSuccessListener<Void>() {
//                    @Override
//                    public void onSuccess(Void aVoid) {
//                        NIM.setText("");
//                        Nama.setText("");
//                        Phone.setText("");
//                        Email.setText("");
//                        IPK.setText("");
//                        Alamat.setText("");
//                        Tanggal.setText("");
//                        Toast.makeText(UpdateActivity.this, "Data Terupdate", Toast.LENGTH_SHORT).show();
//                        finish();
//                    }
//                });
//    }

    //    Pilih gambar
    private void getimage() {
        AlertDialog.Builder dialog = new AlertDialog.Builder(this).setTitle("Upload Image").setItems(new CharSequence[]{"Galeri"}, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                UpdateActivity.this.startActivityForResult(new Intent("android.intent.action.PICK", MediaStore.Images.Media.EXTERNAL_CONTENT_URI), 2);
            }
        });
        dialog.create();
        dialog.show();
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 2 && resultCode == -1 && data != null) {
            try {
                bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), data.getData());
            }catch (IOException e){
                e.printStackTrace();
            }
            Uri data2 = data.getData();
            this.gambarUri = data2;
            this.ViewGambar.setImageURI(data2);
        }
    }

    private void checkUser(){
        if(isEmpty(getNIM) && isEmpty(getNama) && isEmpty(getTanggal_Lahir) && isEmpty(getPhone) && isEmpty(getEmail) && isEmpty(getIPK) && isEmpty(getAlamat)) {
            Toast.makeText(UpdateActivity.this, "Data tidak boleh ada yang kosong", Toast.LENGTH_SHORT).show();
        }else{
            String getKey = getIntent().getExtras().getString("getPrimaryKey");
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG,100,stream);
            reference.child("gambar/"+(UUID.randomUUID() + ".jpg")).putBytes(stream.toByteArray()).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                    taskSnapshot.getStorage().getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                        @Override
                        public void onSuccess(Uri uri) {
                            UpdateActivity.this.getReference.child("Admin").child("Mahasiswa").child(getKey)
                                    .setValue(new com.example.presentasi.data_mahasiswa(getNIM, getNama, getFakultas, getProdi, getGolongan_Darah, getJenis_Kelamin, getTanggal_Lahir, getPhone, getEmail, getIPK, getAlamat, uri.toString().trim()))
                                    .addOnCompleteListener(new OnCompleteListener<Void>() {
                                        @Override
                                        public void onComplete(@NonNull Task<Void> task) {
                                            NIM.setText("");
                                            Nama.setText("");
                                            Fakultas.setSelection(0);
                                            Prodi.setSelection(0);

                                            if(gdA.isChecked()){
                                                gdA.setChecked(false);
                                            }else if (gdB.isChecked()){
                                                gdB.setChecked(false);
                                            }else if (gdAB.isChecked()){
                                                gdAB.setChecked(false);
                                            }else if (gdO.isChecked()){
                                                gdO.setChecked(false);
                                            }

                                            if(Pria.isChecked()){
                                                Pria.setChecked(false);
                                            }else if(Wanita.isChecked()){
                                                Wanita.setChecked(false);
                                            }
                                            Tanggal.setText("klik untuk memilih tanggal lahir");
                                            Phone.setText("");
                                            Email.setText("");
                                            IPK.setText("");
                                            Alamat.setText("");;
                                            Toast.makeText(UpdateActivity.this,"Upload Berhasil",Toast.LENGTH_SHORT).show();
                                            UpdateActivity.this.ViewGambar.setImageResource(R.drawable.ic_baseline_person_100);
                                            startActivity(new Intent(UpdateActivity.this,ListData.class));
                                        }
                                    });

                        }
                    });
                }
            });
        }
    }

}

Here is the simple code
How do I send
                                bundle.putString("dataGambar",listMahasiswa.get(position).getGambar());

How do I receive
        int resId =  getIntent().getExtras().getInt("dataGambar");
        ViewGambar.setImageResource(resId);

Comment: Well what goes wrong? We cannot see what you send as what would be `listMahasiswa.get(position).getGambar()` ? But when it is a resource id integer it is ok.
Answer: The way to transfer an image to another image is by converting the image to a byte array.
To do that we first have to convert the image to a Bitmap.

Converting image to bitmap

Bitmap myLogo = BitmapFactory.decodeResource(context.getResources(), R.drawable.my_drawable);
Ref:How to convert a Drawable image from resources to a Bitmap

Convert Bitmap to Byte Array

Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();

Ref:converting Java bitmap to byte array

Pass array to intent

  Intent intent = new Intent(this, NextActivity.class);
intent.putExtra("picture", byteArray);
startActivity(intent);

get tha value in next activity

Bundle extras = getIntent().getExtras();
byte[] byteArray = extras.getByteArray("picture");

Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
ImageView image = (ImageView) findViewById(R.id.imageView1);

image.setImageBitmap(bmp);


Is this a Waltz music?

Question: I am starting to playing a piano and I am new to a aclassical dance.
I was googling some Waltz songs, that I could play on a piano. I found Beuty and the Beast song, that was marked as a Waltz. But I was looking to the sheet music at the internet and I found that it is played on four times (4/4). Isn't the Waltz supposed to be three times song (3/4)?
Thank you very much for explanation
Answer: "Beauty and the Beast" in its standard form is a pop ballad in 4/4 time, not a waltz. However, many times in musicals and musical theater they will do an alternate version of a song with a different feel and tempo. Sometimes it is for background music or a dance scene or a reprise. There is a waltz section in 3/4 time in this version of the song for a dance sequence. It starts a little past the 1 minute mark:

Like I said before though, this is not a typical version of this song.
Comment: (My favorite such re-metering is how *The Sound of Music* recasts "The lonely goatherd" as a ländler for the party scene.)
Answer: As already pointed out, the song itself is in 4/4 time. However, in the original animated movie, Beauty and the Beast are dancing a waltz — or at least something very waltz-like.
Dance scene from the 1991 movie

Waltzes are indeed in 3/4 time.
Dance set to Johann Strauss's "Blue Danube" Waltz

See also John Belzaguy's answer explaining how the song can be arranged into a waltz.

Is this a Waltz music?


Tabs dentro de um modal ao clicar desaparece o modal

Question: Estou implementando um modal e dentro dele estou colocando tabs.
Porém quando eu clico em alguma aba da tab o modal desaparece.
Vejam as imagens.
Uso o bootstrap.

Notem que a url muda..
como resolver ??
meu html

    Saúde

Pacientes

                    <button id="btnSalvar" type="button" data-toggle="modal" data-target="#modalAdicionarPaciente" class="btn btn-default ">Adicionar novo paciente</button>
                    <button id="btnImprimir" type="button"  class="btn btn-default pull-right ">Imprimir</button>

                                    Id
                                    Foto
                                    Nome
                                    Idade

                                    {{}}
                                    {{}}
                                    {{}}

                                            <button id="opcoes" type="button" class="btn btn-danger vermDigifred btn-xs dropdown-toggle glyphicon glyphicon-pencil" data-toggle="dropdown"> </button>

 Excluir registro

  Alterar registro

                    <button type="button" class="close" data-dismiss="modal">×</button>

                        Adicionar Paciente

                    <form novalidate name="frmPaciente" id="formCadastro" role="form">

                                      <input type="file" id="file"   fileinput="file" filepreview="filepreview"  />

                                Nome *: <input maxlength="70" required="required" type="text" class="form-control" ng-model="distrito.nome" />

                                CNS *: <input maxlength="70" required="required" type="text" class="form-control" ng-model="distrito.nome" />

                                Nome Social *: <input maxlength="70" required="required" type="text" class="form-control" ng-model="distrito.nome" />

                                Sexo: <select ng-model="distrito.municipio.idMunicipio" class="form-control">
                                    <option value="{{dis.entidade.municipio.idMunicipio}}" ng-repeat="dis in distritos">{{dis.entidade.municipio.nome}}</option>
                                </select>

                                Data Nascimento: <input maxlength="70" required="required" type="text" class="form-control" ng-model="distrito.nome" />

                                Idade: <input maxlength="70" required="required" type="text" class="form-control" ng-model="distrito.nome" />

Dados

Documentos

Pacientes

Características

Personalizados

Some content.

Some content in menu 1.

Some content in menu 2.

Some content in menu 2.

Some content in menu 2.

                    </form>

                    <button style="background-color: #b51e27; color: white;" type="button" class="btn btn-default" data-dismiss="modal" ng-click="salvarPacientes()">Salvar</button>
                    <button style="background-color: #b51e27; color: white;" type="button" class="btn btn-default" ng-click="salvarPacientes()">Salvar e novo</button>
                    <button style="background-color: #b51e27; color: white;" type="button" class="btn btn-default"  ng-click="cancelarAlteracaoPacientes(pac)" data-dismiss="modal">Cancelar</button>

Answer: Veja como está a importação do css e do seu js no header do html
veja a sequencia.

CSS do Bootstrap
CSS customizado
JQuery
JS do Bootstrap
JS customizado

Sendo que os arquivos .JS podem ficar no final do documento antes do fechamento da tag

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

Pacientes

        <button id="btnSalvar" type="button" data-toggle="modal" data-target="#modalAdicionarPaciente" class="btn btn-default ">Adicionar novo paciente</button>
        <button id="btnImprimir" type="button" class="btn btn-default pull-right ">Imprimir</button>

                Id
                Foto
                Nome
                Idade

                {{}}
                {{}}
                {{}}

                    <button id="opcoes" type="button" class="btn btn-danger vermDigifred btn-xs dropdown-toggle glyphicon glyphicon-pencil" data-toggle="dropdown"> </button>

 Excluir registro

  Alterar registro

        <button type="button" class="close" data-dismiss="modal">×</button>

          Adicionar Paciente

        <form novalidate name="frmPaciente" id="formCadastro" role="form">

                  <input type="file" id="file" fileinput="file" filepreview="filepreview" />

              Nome *: <input maxlength="70" required="required" type="text" class="form-control" ng-model="distrito.nome" />

              CNS *: <input maxlength="70" required="required" type="text" class="form-control" ng-model="distrito.nome" />

              Nome Social *: <input maxlength="70" required="required" type="text" class="form-control" ng-model="distrito.nome" />

              Sexo: <select ng-model="distrito.municipio.idMunicipio" class="form-control">
                                    <option value="{{dis.entidade.municipio.idMunicipio}}" ng-repeat="dis in distritos">{{dis.entidade.municipio.nome}}</option>
                                </select>

              Data Nascimento: <input maxlength="70" required="required" type="text" class="form-control" ng-model="distrito.nome" />

              Idade: <input maxlength="70" required="required" type="text" class="form-control" ng-model="distrito.nome" />

Dados

Documentos

Pacientes

Características

Personalizados

Some content.

Some content in menu 1.

Some content in menu 2.

Some content in menu 2.

Some content in menu 2.

        </form>

        <button style="background-color: #b51e27; color: white;" type="button" class="btn btn-default" data-dismiss="modal" ng-click="salvarPacientes()">Salvar</button>
        <button style="background-color: #b51e27; color: white;" type="button" class="btn btn-default" ng-click="salvarPacientes()">Salvar e novo</button>
        <button style="background-color: #b51e27; color: white;" type="button" class="btn btn-default" ng-click="cancelarAlteracaoPacientes(pac)" data-dismiss="modal">Cancelar</button>


How to get user dictionary in Google translate Api

Question: I would like to make some website with remembered translations in google translate. I think that getting user saved translations is not possible but maybe anyone know some way to do this. I saw that google translate api provide not many endpoints, there is endpoints for detecting languages, translatios and providing available languages.
Does anyone know how to get saved vocabulary?
Comment: by saved/user vocabulary you mean the phrasebook that can be inspected from https://translate.google.com/ when logged in?
Comment: I'm not sure if we meaning the same. In the picture i marked the section with saved user words.
Comment: Yes, we mean the same. See my answer.
Comment: Would you please confirm whether the provided answer is helpful or not?
Comment: Sure, Thanks for help.
Answer: Unfortunately, there is no way to retrieve the saved vocabulary (aka phrasebook)
There is an existing feature request asking for some sort of access (a Phrasebook API?) to this data. I'd suggest you to star the issue and show your interest, in order to attract its developer's attention and increase the chances that'll be implemented.