Why is this part of the composed proposition false?

Question: Currently I'm studying logic, but I do not understand a certain step. It is the step from row $2$ to $3$. I see that $-q$ is the common factor on both sides of the middle or operator, but I did not succeed in factoring out.
\begin{equation}
\begin{aligned}
(p \wedge q) \rightarrow \neg(r \vee q) & \equiv \neg(p \wedge q) \vee \neg(r \vee q) \\
& \equiv \neg p \vee \neg q \vee(\neg r \wedge \neg q) \\
& \equiv \neg p \vee \neg q
\end{aligned}
\end{equation}
I understand that
\begin{equation}
\begin{aligned}
&\equiv \mathbb{F} \vee(p \wedge q) \\
&\equiv(p \wedge q)
\end{aligned}
\end{equation}
so that implies that
\begin{equation}
(\neg \boldsymbol{r} \wedge \neg q)
\end{equation}
is false.
Do I miss a rule or should it be obvious from the K-map?
Whole question + solution:
Comment: It's definitely an equivalence. Do you know what absorption is?
Comment: @TenO'Four Now it looks correct I added a proof.
Comment: @Tim, here's [proof](https://math.stackexchange.com/questions/536111/explain-the-absorption-law) of the law (see the last answer)
Comment: Thanks for the help!
Comment: Thanks for the feedback, I included the whole question to make sure I didnot include essential information
Comment: I mixed two past papers. Now it should be 'correct'
Comment: I checked it on wikipedia. But I don't see yet how the prove equivalence
Comment: @Voilet Flame, while correct I'm not sure it will help Tim much. They're probs looking for a list of equivalences — comp sci loves their equivalences lol
Comment: @Tim, this is [absorption](https://en.m.wikipedia.org/wiki/Absorption_law) — $\lnot q\lor (\lnot r\land\lnot q)\equiv\lnot q$
Answer:
$\neg p\lor \neg q\equiv \neg p \vee \neg q \vee(\neg r \wedge \neg q) \\$

Is indeed true, one direction of the equivalence is trivial, for the other direction suppose that  $\neg p \lor \neg q \lor (\neg r \land  \neg q) $ is true then we must have that at least one of the disjuncts is true. Now suppose  that $(\neg r \land \neg q$) is true then we immediately have that $\neg q$ is true and so we get $\neg p\lor \neg q$ is true. If the other disjunct is true then we have a triviality.
Answer: First, I want to point out a mistake in your reasoning. You say:

I understand that

\begin{equation}
\begin{aligned}
&\equiv \mathbb{F} \vee(p \wedge q) \\
&\equiv(p \wedge q)
\end{aligned}
\end{equation}

so that implies that

\begin{equation}
(\neg \boldsymbol{r} \wedge \neg q)
\end{equation}

is false.

No, that does not follow. (and obviously $\neg r \land \neg q$ is not equivalent to $False$)
Consider: $p \lor p \equiv p$ ... so by your logic, we would have to have that $p \equiv False$?
Clearly something is wrong with your logic. At its core, what you are doing is this:
We know that if $\psi \equiv False$, then $\phi \lor \psi \equiv \phi$. But the converse is not true: if $\phi \lor \psi \equiv \phi$, then $\psi \equiv False$. In effect, you are making the logical fallacy of affirming the consequent.
OK, but why does the converse not hold? What follows below will provide some further insight.
As a general helpful principle, note that $p \lor (p \land q) \equiv p$:
$$p \lor (p \land q) \equiv p$$
$$\overset{Identity}{\equiv}$$
$$(p \land \top) \lor (p \land q)$$
$$\overset{Distribution}{\equiv}$$
$$p \land (\top \lor q)$$
$$\overset{Annihilation}{\equiv}$$
$$p  \land \top$$
$$\overset{Identity}{\equiv}$$
$$p$$
That first step is a little tricky, but you can also think of this as:
$p + pq = p(1+q) = p1 = p$
This principle is so common, that is has a name:
Absorption
$p + pq = p$
and its dual: $p(p+q) = p$
So, if you apply Absorption to your statement, you get:
$$\neg p \lor \neg q \lor (\neg r \land \neg q)$$
$$\overset{Absorption}{\equiv}$$
$$\neg p \vee \neg q$$
Yeah, it's that easy. So make sure to put Absorption in your Boolean Algebra toolkit!
Also if you look at what happens in a K-Map, you'll immediately notice why it's called Absorption:  The one term is 'absorbed' by the other term: that's why it can be removed!
So, going back to your earlier mistake:  $p \lor p \equiv p$ not because $p \equiv False$, but because the second $p$ is already covered by the first $p$.  Put differently: it's not that the second $p$ is doing nothing but because the second $p$ term isn't doing anything over and above the first term.
Likewise, $\neg q \lor (\neg r \land \neg q) \equiv \neg q$ not because $\neg r \land \neg q$ is doing nothing, but because it is doing nothing over and above $\neg q$ by itself: the $\neg q$ 'covers', and thus 'absorbs' the $\neg r \land \neg q$ term
Comment: Thank you for the elaborate answer!
Comment: @Tim You're welcome!
Comment: It's a great answer that deserves to be accepted!
Comment: Thanks @VoiletFlame !


Finding the limit $ \lim_{x\to 0}\frac{(1-3x)^\frac{1}{3} -(1-2x)^\frac{1}{2}}{1-\cos(\pi x)}$

Question: I cannot find this limit:
$$
\lim_{x\to 0}\frac{(1-3x)^\frac{1}{3} -(1-2x)^\frac{1}{2}}{1-\cos(\pi x)}.
$$
Please, help me.
Upd: I need to solve it without L'Hôpital's Rule and Taylor expansion.
Comment: @DanielFischer Asking to to this without Taylor expansion this should be considered torture, therefore banned by the Geneva convention.
Comment: Taylor expansion to second order helps.
Comment: You can also use LHopital rule
Comment: Ok, I saw your update after I posted my answer. Too bad, since I'm afraid that I agree with egreg: this exercise without l'H and/or Taylor expansions and chemical weapons should be allowed only in cases of extremely terrible students.
Comment: Is this homework?
Comment: @freak_warrior yes, it is. I have been trying to do this task for hours =( I cannot use l'H and Taylor because we didnot learn it.
Comment: @user109428: So what have you all learned? Can you show us?
Comment: we have learned some basic things of finding limits of sequences and functions. The last theme was about limits of special interest.
Answer: Write it as $\left(\frac{\cos\pi x-\cos0}{x-0}\right)^{-1}\times\frac{\left(1-3x\right)^{\frac{1}{3}}-\left(1-2x\right)^{\frac{1}{2}}}{x-0}$.
Then $\lim_{x\rightarrow0}\frac{\cos\pi x-\cos0}{x-0}$ can be recognized
as $f'\left(0\right)$ for $f\left(x\right)=\cos\pi x$
and $\lim_{x\rightarrow0}\frac{\left(1-3x\right)^{\frac{1}{3}}-\left(1-2x\right)^{\frac{1}{2}}}{x-0}$
as $g'\left(0\right)$ for $g\left(x\right)=\left(1-3x\right)^{\frac{1}{3}}-\left(1-2x\right)^{\frac{1}{2}}$.
If you are blamed to use de l'Hôpital after all then just claim that
you were not aware of that. They will believe you.
Edit:
This only works if $f'\left(0\right)\neq0$ and unfortunately
that is not the case here.
So to be honest: this does not answer your question. Keep it in mind
however for next occasions.
Comment: I would say you got upvotes because of the "They will believe you" part (which is nice, mind you) and because many voters simply do not read/master/check the maths. Anyway, you are not responsible for that and, with the Edit, there is nothing to say against your post.
Comment: This expresses the limit as $f'(0)/g'(0)$ for some functions $f$ and $g$ such that $f'(0)=g'(0)=0$. (Nice upvotes though, would you have a fan club?)
Comment: @did Sigh... I did not bother to look at the outcomes. Now what to do? Delete it and throw away my upvotes? I think people liked it especially because of the sneaky use of l'Hopital. I will make an edit. Fanclub... I enjoy the thought.
Answer: Solving this without Taylor expansion is quite artificial, if you ask me (any justification, pedagogical or otherwise?), hence here we go for artificiality.
If $u\to1$ and $v\to1$,
$$
u^{1/6}-v^{1/6}=\frac{u-v}{u^{5/6}+u^{4/6}v^{1/6}+u^{3/6}v^{2/6}+u^{2/6}v^{3/6}+u^{1/6}v^{4/6}+v^{5/6}},
$$
and each term in the denominator has limit $1$ hence
$$
u^{1/6}-v^{1/6}\sim\frac{u-v}6.
$$
Using this for $u=(1-3x)^2$ and $v=(1-2x)^3$ yields $u-v=-3x^2+8x^3$ hence
$$u-v\sim-3x^2.
$$
On the other hand, $1-\cos(\pi x)=2\sin^2\left(\frac12\pi x\right)$ and $\sin t\sim t$ (but are we allowed to use this? this is Taylor, after all...) hence
$$1-\cos(\pi x)\sim2\left(\frac12\pi x\right)^2=\frac12\pi^2x^2.$$
Thus, the limit of the ratio is
$$
\frac{-3\cdot\frac16}{\frac12\pi^2}=-\frac1{\pi^2}.
$$
Comment: There is a $\frac{1}{6}$ missing in exponents of the denominator.
Comment: @Xoff Right, thanks.
Answer: l'Hospital:
$$\lim_{x\to 0}\frac{(1-3x)^{1/3}-(1-2x)^{1/2}}{1-\cos \pi x}\stackrel{\text{l'H}}=\lim_{x\to 0}\frac{-(1-3x)^{-2/3}+(1-2x)^{-1/2}}{\pi\sin\pi x}\stackrel{\text{l'H}}=$$
$$=\lim_{x\to 0}\frac{-2(1-3x)^{-5/3}+(1-2x)^{-3/2}}{\pi^2\cos\pi x}=-\frac1{\pi^2}$$
Comment: Yes, he did...after or while I wrote and posted my answer. It stays in case someone wants to check how to do it without being forced to sell one's soul to some god or devil.
Comment: OP stated no LHopital
Comment: @freak_warrior But this is l'Hospital
Answer: Your limit is
$$\lim_{x\to 0} \frac{(1-3x)^\frac{1}{3}-(1-2x)^{\frac{1}{2} } }{1-\cos\pi x }$$
$$=\lim_{x\to 0} \frac{(1-3x)^\frac{1}{3}-(1-2x)^{\frac{1}{2} } }{1-\cos\pi x }\cdot \frac{1+\cos(\pi x)}{1+\cos(\pi x)}$$
$$=\lim_{x\to 0} \frac{\left((1-3x)^\frac{1}{3}-(1-2x)^{\frac{1}{2} }\right)(1+\cos(\pi x)) }{1-\cos^2\pi x }$$
$$=\lim_{x\to 0} \frac{\left((1-3x)^\frac{1}{3}-(1-2x)^{\frac{1}{2} }\right)(1+\cos(\pi x)) }{\sin^2\pi x }$$
$$=\lim_{x\to 0} \frac{\left((1-3x)^\frac{2}{3}-(1-2x)\right)(1+\cos(\pi x)) }{\left((1-3x)^\frac{1}{3}+(1-2x)^{\frac{1}{2} }\right)\sin^2\pi x } $$
$$=\lim_{x\to 0} \frac{\left((1-3x)^\frac{2}{3}-(1-2x)\right) }{\sin^2\pi x } $$
$$=\lim_{x\to 0} \frac{\left((1-3x)^{2}-(1-2x)^3\right) }{(P(x))\sin^2\pi x } $$
$\lim_{x\to 0} P(x)=3$. Here $P(x)=(1-3x)^{\frac{4}{3}}+(1-3x)^{\frac{1}{3}}(1-2x)+(1-2x)^2$.
Now, $$\lim_{x\to 0} \frac{\left((1-3x)^{2}-(1-2x)^3\right) }{\sin^2\pi x }=-\frac{3}{\pi^2}$$ because
$$=\lim_{x\to 0} \frac{\frac{(1-3x)^{2}-(1-2x)^3}{\pi^2 x^2} }{\frac{\sin^2\pi x}{\pi^2 x^2}}$$
$$=\lim_{x\to 0} \frac{(1-3x)^{2}-(1-2x)^3}{\pi^2 x^2}=\lim_{x\to 0} \frac{8x^3-3x^2}{\pi^2 x^2}=-\frac{3}{\pi^2}$$
Thus your limit is equal to
$$\frac{-3}{\pi^2}\cdot \frac{1}{3}=-\frac{1}{\pi^2}$$
Comment: In this proof i use several facts: $\lim_{x\to 0}\frac{\sin x}{x}=1$. If $\lim fg$ exist an $\lim g$ exist then $\lim f$ also exist.
Comment: "If lim fg exist(s) an(d) lim g exist(s) then lim f also exist(s)". Sure about this one?
Comment: You rigth. And $\lim g(x)\neq 0$ And if $g(x)\neq 0$ for all $x$ near to $0$ in this case.
Comment: Rather, if lim g is not zero.


How do I make an archived-dump of my site?

Question: I have multiple versions of drush and cannot make an archive-dump of my site.
drush8 ard/drush8 archive-dump returns

[error]  The drush command 'ard' (and/or 'archive-dump') could not be found.  Run drush
  cache-clear drush to clear the commandfile cache if you have
  installed new extensions.

drush6 ard/drush6 archive-dump returns

Drush 6.6.0 does not support Drupal . See
  http://drupal.org/project/drush for more information.
  [error] Command archive-dump needs a higher bootstrap level to run -
  you will need to invoke drush from a more functional Drupal
  environment to run[error] this command. The drush command
  'archive-dump' could not be executed.

drush ard/drush archive-dump returns

PHP Fatal error:  Class 'Drupal\Core\Session\AccountInterface' not
  found in /var/www/mywebsite/core/includes/bootstrap.inc on line 60

drush8 = * remote origin
  Fetch URL: https://github.com/drush-ops/drush.git
  Push  URL: https://github.com/drush-ops/drush.git
drush6 = * remote origin
  Fetch URL: https://github.com/drush-ops/drush.git
  Push  URL: https://github.com/drush-ops/drush.git
drush =  Drush Version:6.2.0

If I run drush8 status on my local site it returns

Drush:9.0-dev-g9bbddb2

If I run drush6 status on my local site it returns

Drush 6.6.0 does not support Drupal . See http://drupal.org/project/drush for more information.

If I run drush status on my local site it returns

PHP Fatal error:  Class 'Drupal\Core\Session\AccountInterface' not found in /var/www/mywebsite/core/includes/bootstrap.inc on line 60
  Drush command terminated abnormally due to an unrecoverable error.                                                                         [error]
  Error: Class 'Drupal\Core\Session\AccountInterface' not found in /var/www/mywebsite/core/includes/bootstrap.inc, line 60
Comment: Only Drush 8+ supports Drupal 8. [Drush install docs](http://www.drush.org/en/master/install/)
Comment: this is exactly the mental nudge I needed. I went back into drush8 and checked out the 8.x version of drush and it works as expected.
Comment: Please highlight this in your post, so people won't have to read in the comments!
Comment: PHP 5.6.3-1+deb.sury.org~trusty+1 (cli)
Comment: @ponies You should make your comment an answer, so the question doesn't show up in the unanswered list.
Answer:
Drush 8 supports: Drupal 7->8.3
Drush 10 supports: Drupal 8.4->9

The Drush\Drupal Compatibility chart: https://www.drush.org/latest/install/#drupal-compatibility
Drush 8 is expected to go end of life with Drupal 7 in November 2022.
More information about ard in drush 9: https://github.com/pantheon-systems/documentation/issues/3946#issuecomment-467963427


How do I make Tomcat start automatically?

Question: I'm trying to get Tomcat to start automatically, and I'm failing miserably. (It's Tomcat 6.0.16 running on Fedora 8, based on Amazon ami-11ca2d78.) So, following standard instructions, I've created /etc/init.d/tomcat containing this:
 export JRE_HOME=/env/jdk1.6.0_07/jre/
 case $1 in
 start)
        sh /env/tomcat/bin/startup.sh
        ;;
 stop)
        sh /env/tomcat/bin/shutdown.sh
        ;;
restart)
        sh /env/tomcat/bin/shutdown.sh
        sh /env/tomcat/bin/startup.sh
         ;;
esac
exit 0

And I chmod 755 it. Then I create soft links:
ln -s /etc/init.d/tomcat /etc/rc1.d/K99tomcat
ln -s /etc/init.d/tomcat /etc/rc2.d/S99tomcat

But when I reboot it fails, and the logs show this exception:
java.lang.IllegalArgumentException: Document base /env/tomcat/webapps/QCServer does not exist or is not a readable directory
But if I run /etc/init.d/tomcat start directly from the command line, everything works fine. And this is a readable directory, with r+x privileges for everyone. So what on earth am I doing wrong? Thanks very much for any help!
AC
Comment: Out of curiosity: Why on earth are you still using Fedora 8? It has seen it's end of life long time ago (see http://fedoraproject.org/wiki/End_of_life).
Comment: Because that's what Amazon's ami-11ca2d78 is based upon. I want to be able to easily launch my java web app to EC2, preferably from Eclipse, and this is the best ami I've found for the purpose. If you know a better one, please let me know. I'd rather not have to spend endless hours fiddling around configuring such an ami from scratch. I agree, I'd rather use latest releases, but latest releases tend to break other stuff. For example, I need to use Tomcat 6.0.16 on the server, or Eclipse chokes on it. Again, if you know a better alternative I'd love to hear about it. - AC
Answer: If it is readable then the problem is that it can't find the directory. When you started tomcat by hand, you were logged in as 'root' user, I'm guessing. The user has CATALINA_HOME setup to point to where tomcat is installed. I think the problem is tomcat can't find the application base directory.
In server.xml file, where you specified the base directory for 'QCServe', use full path instead of relative path. If you application is installed in /opt/apps/tomcat/webapps/QCServe, then put that absolute path there.
-N
Comment: Alternatively, you can add export CATALINA_HOME=/location/to/tomcat   in the /etc/init.d/tomcat file and that should solve the problem. If you have other env variables relating to tomcat, put it in /etc/init.d/tomcat file.
Answer: What runlevel are you running?
Create the link in /etc/rc3.d
Answer: Save as /etc/init.d/tomcat, chkconfig add tomcat. Edit the values at the top as needed to tailor to your installation; the values presented are just an example (especially JAVA_OPTS memory settings).
#!/bin/sh
#
# Startup script for Tomcat
#
# chkconfig: 345 82 20
# description: Tomcat is a servlet runner

JAVA_HOME=/usr/local/java
TOMCAT_HOME=/usr/local/tomcat
XMFILE=$TOMCAT_HOME/conf/server.xml
JAVA_OPTS="-server -Xms1536m -Xmx1536m -Xmn384m -XX:+UseParallelGC"
CATALINA_OPTS=""
export JAVA_HOME TOMCAT_HOME JAVA_OPTS CATALINA_OPTS

# See how we were called.
case "$1" in
  start)
    cd $TOMCAT_HOME
    ./bin/startup.sh -config $XMFILE
    ;;
  stop)
    cd $TOMCAT_HOME
    ./bin/shutdown.sh -config $XMFILE
    ;;
  restart)
    $0 stop
    sleep 3
    $0 start
    ;;
  *)
    echo "Usage: $0 {start|stop|restart}"
    exit 1
esac

exit 0


How to Search and output from Meteor Collection

Question: The JS
Colors = new Meteor.Collection("colors");

Template.col_list.cols = function () {
  return Colors.find();
};

So this code will output everything from Col.find into the handlebar cols in the html
The HTML
{{#each cols}}
{{name}}, {{RGB}}, {{HEX}}
{{/each}}

But say I want to have a input box so I can search for a name of the color, so it only shows the information for that color or any color that starts with whatever I type into the input box.
example:
Input = "bl"
output should be black, blue or whatever else that starts with bl.
I've been looking everywhere for any example of this in practice yet I haven't found any.
Far as I have gotten so far is something to this effect yet it yields no luck.
Template.col_list.events({
  'click .search': function() {
    Colors.find(name: $('col_name').val());
  }
});

Answer: You need to make the content of the template depend on the input field in a way that preserves the reactivity of Meteor. Session variables are great for that.
This should work:
Colors = new Meteor.Collection("colors");

Template.col_list.cols = function () {
  return Colors.find({name: { $regex: Session.get('prefix')+".*", $options: 'i' }});
};

Template.col_list.events({
  'click .search': function() {
    Session.set('prefix', $('.col_name').val());
  }
});

Comment: OK, then your jquery selector was off. I've updated my answer. You need to use ".col_name" to find that element. Does this fix the "undefined" issue?
Comment: tried it, nothing happened, tried adding alert('Searching for ' + $('col_name').val()); It says that im searching for undefined :/
Comment: tried adding undefined to the database and it finds undefined :P so we know it should work but why is it undefined?
Comment: We will need to see your input HTML for that, i.e., where us col_name defined? BTW, you probably mean "#col_name", no?
Comment:
Comment: indeed it does :D silly me I knew that it needed to be .classname yet somehow when I retyped the javascript I didnt put a . there :S Thanks so much for the help
Comment: final short question: do you know how I can make it so it doesnt care if the name is capitalized or not.
Comment: Yes. I've updated the answer once more (you need to add the 'i' option to the regex).


step counting sensor not working on real devices

Question: i have code for step counting sensor
but i run this code on my devices and it is not working
override fun init_events() {

        sensoreManager=getSystemService(Context.SENSOR_SERVICE) as SensorManager
        if(sensoreManager!!.getDefaultSensor(Sensor.TYPE_STEP_COUNTER)!=null)
        {

            sensor=sensoreManager!!.getDefaultSensor(Sensor.TYPE_STEP_COUNTER)
            running=true
            showToastMessage("yes")
        }else{
           showToastMessage("no")
            running=false
        }

}

    override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {
        Log.i("TEST_TEST","ssssssssssss")

    }

    @SuppressLint("SetTextI18n")
    override fun onSensorChanged(event: SensorEvent?) {
        Log.i("TEST_TEST","ssssssssssss")
        if(event!!.sensor==sensor)
            showToastMessage("movment")

    }

    override fun onResume() {
        Log.i("TEST_TEST","f RESume")

        super.onResume()
        if(sensoreManager!!.getDefaultSensor(Sensor.TYPE_STEP_COUNTER)!=null){
            sensoreManager!!.registerListener(this,sensor,SensorManager.SENSOR_DELAY_FASTEST)
            Log.i("TEST_TEST","not null")}
        else{
            Log.i("TEST_TEST","null")
        }
    }

    override fun onPause() {
        Log.i("TEST_TEST","f onPause")
        super.onPause()
        if(sensoreManager!!.getDefaultSensor(Sensor.TYPE_STEP_COUNTER)!=null)
           sensoreManager!!.unregisterListener(this,sensor)
    }

what wrong on this code
my device xiaomi note 9 pro
Comment: https://stackoverflow.com/questions/59592685/android-10-cannot-register-sensor-type-step-counter
Comment: Does the accelerometer of the device work in any other apps on the phone?
Comment: Yes i download many apps on google play and it work
Answer: the anser in this code
you have to accept permission in android 10
if(ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACTIVITY_RECOGNITION) == PackageManager.PERMISSION_DENIED){
        //ask for permission
        requestPermissions(new String[]{Manifest.permission.ACTIVITY_RECOGNITION}, PHYISCAL_ACTIVITY);
    }
    ```


convergence in $L^1$ for product of functions

Question: If $f_n$ converges to $f$ in $L^1$ and $g_n$ converges to $g$ in $L^1$. Does it necessarily mean that $f_ng_n$ converges to $fg$ in $L^1$ for finite measure spaces.
Comment: No, to begin with, $fg$ need not be in $L^1$.
Answer: As Did already pointed out, $f \cdot g$ and $f_n \cdot g_n$ are in general not integrable, therefore we need stronger assumptions. Using the ($L^1$-)triangle inequality and Hölder's inequality, it's not difficult to prove the following result:

Let $f_n \to f$ in $L^2$ and $g_n \to g$ in $L^2$. Then $f_n \cdot g_n \to f \cdot g$ in $L^1$.
Comment: Is it the $L^1$-triangular inequality? $\|f_ng_n-fg\|_{L^1}=\|(f_n-f)g_n+f(g_n-g)\|_{L^1}\le \|(f_n-f)g_n\|_{L^1}+\|f(g_n-g)\|_{L^1}\le\| f_n-f\|_{L^2}\| g_n\|_L^2+\|f\|_{L^2}\|g_n-g\|_{L^2}$
Comment: @roi_saumon Your reasoning is fine, though it's Hölder's inequality which you need (rather than the triangle inequality in $L^1$)
Comment: Yes, for the last step. But what did you have in mind with $L^2$-triangular inequality?
Comment: @roi_saumon Ah, that's what you meant. Yes, you are right, it's the $L^1$-triangle inequality which one needs to use.
Answer: Of course not. Consider the Lebesgue measure on [0,1] and the functions $f_{n}=g
_{n}=\frac{1}{x^{\frac{1}{2}+\frac{1}{n}}}$ for $n>1$


Dependence of variables - partial differentiation

Question: When doing partial differentiation, I'm having trouble seeing if an expression depends on a variable or not. For example, consider the following expressions:
$$a = x + 2y, $$
$$b = 3x -y,$$
$$z = 3a + 4.$$
So, by blindly differentiating, I can say
$$\frac{\partial z}{\partial b} = 0,$$
since $z$ has no (explicit!) dependence on $b$. However, intuitively, if $b$ changes, $x$ and $y$ may be changing, leading to a change in $a$, and as a result, a  change in $z$, implying that the partial derivative may not be $0$.
How do I reconcile these two notions?
Comment: When you have lots of variables that all depend on each other, like in thermodynamics, it's at least as important to specify the things being held constant as the things that are changing in a partial derivative. The whole point of a partial derivative is that things are held constant, after all. Unfortunately people are lazy and notation like $$\left.\frac{\partial z}{\partial b} \right|_{a,c}$$ is ugly, so people don't often use it.
Answer: Disclaimer: I find this question relatable, so I am going to answer what works for me, although there may be some hand-waving...
The problem has to specify the cause-effect relation among variables. I usually do this with a sequence of transformations represented by arrows. For instance, you can say that you have a couple of fundamental variables $(x,y)$, which are transformed to other pair $(a,b)$ (in this case it is a linear change of basis), which in turn can be used to produce the magnitude $z$. So you have the chain:
$$z\gets (a,b) \gets (x,y)$$
If we assume that this is what is meant by your three equations, then it is true that a change in $(x,y)$ forces a change in $b$, but $z$ is only aware of this because of the change in $a$, so $\frac{\partial z}{\partial b}=0$.
However, imagine we start from the assumption that the fundamental variables are $(a,b)$ and there is the chain:
$$z \gets (x,y) \gets (a,b) $$
where the function $(x,y)=F(a,b)$ is implicit.
Then, your third equation is a (notationally abusive) way to express:
$$z=3(x+2y)+4$$
so you can apply the chain rule to obtain:
$$
\frac{\partial z}{\partial b}=\frac{\partial z}{\partial x}\frac{\partial x}{\partial b}+\frac{\partial z}{\partial y}\frac{\partial y}{\partial b}
$$
To summarize: the relations among variables must be stated as a part of the problem.
Answer: You need to point out what your variables are. If your variables are $a$ and $b$, and  you regard $z$ as $z(a,b)=3a+4$, then $z(a,b)$ is of course independent on $a$.
If you choose $x,y$ as variables, you should write $z=3a(x,y)+4$ to tell yourself that $a$ is the function of variables $x$ and $y$.
Answer: $\frac{\partial z}{\partial b} = 0$ is only true if $\frac{\partial a}{\partial b} = 0$ which it is not given the equations that govern $a$ and $b$. Thus, you made a mistake when you concluded that $\frac{\partial z}{\partial b} = 0$.


ActiveRecord cannot delete a record

Question: I have my AttachmentsMembers table with the migration as:
class AttachmentsMembers < ActiveRecord::Migration
  def change
    create_table :attachments_members, :id => false do |t|
      t.references :attachment, :null => false
      t.references :member, :null => false
    end

    add_index :attachments_members, [:attachment_id, :member_id]
  end
end

If I try to delete any record from my console then I get the following error:
ActiveRecord::StatementInvalid: PG::Error: ERROR:  zero-length delimited identifier at or near """"
LINE 1: ...OM "attachments_members" WHERE "attachments_members"."" = $1
                                                                ^
: DELETE FROM "attachments_members" WHERE "attachments_members"."" = $1
from /home/icicle/.rvm/gems/ruby-2.0.0-p353@ltbuddy/gems/activerecord-3.2.18/lib/active_record/connection_adapters/postgresql_adapter.rb:1208:in `prepare

Code for AttachmentsMember model:
class AttachmentsMember < ActiveRecord::Base
  #Relationships
  belongs_to :attachment
  belongs_to :member
end

In attachment model:
  belongs_to :user, class_name: 'User', foreign_key: 'user_id'
  belongs_to :attachable, polymorphic: true
  belongs_to :referable, polymorphic: true

  has_many :attachments, as: :referable, :dependent => :destroy

  has_many :attachments_members, :dependent => :destroy
  has_many :members, :through => :attachments_members, :dependent => :destroy

In member model:
  belongs_to :user, class_name: 'User', foreign_key: 'user_id'
  belongs_to :case, class_name: 'Case', foreign_key: 'case_id'
  belongs_to :user_type, class_name: 'UserType', foreign_key: 'user_type_id'

  has_many :attachments_members, dependent: :destroy
  has_many :attachments, :through => :attachments_members, dependent: :destroy

  has_many :documents_members, dependent: :destroy
  has_many :documents, :through => :documents_members, dependent: :destroy

Even if do AttachmentsMember.last from my console I get the same error but AttachmentsMember.first works.
Any someone explain why the issue is coming?
Comment: Resolved the issue by creating the primary key for AttachmentsMember table
Comment: Can you please show the model, and also the command you are using in the console?
Comment: @WayneConrad have editted the post
Comment: Can someone please tell me the reason for the above issue?
Comment: You can answer your own question, and then give it the answer the checkmark.  This may help someone in the future.
Answer: Resolved the issue by creating the primary key for AttachmentsMember table

ActiveRecord cannot delete a record


How can I stop warnings about unused private fields?

Question: While compiling a collection of files in a Qt project, I'm seeing lots of warnings similar to this one.
In file included from /usr/local/Trolltech/Qt-4.8.6/include/QtGui/qevent.h:52:
/usr/local/Trolltech/Qt-4.8.6/include/QtGui/qmime.h:119:10: warning: private field 'type' is not used [-Wunused-private-field]
    char type;
     ^

Per suggestions from various searches, I did add the entry
QMAKE_CXXFLAGS += -Wno-unused-private-field
to the .pro file and confirmed that it shows up properly in compiler invocations but I'm still getting that warning.
I'm running Qt on a Mac with clang.
Thanks in advance for any insights.
Answer: Per this answer, try
QMAKE_CXXFLAGS_WARN_ON += -Wno-unused-private-field

It appears that the QMAKE_CXXFLAGS_WARN_ON flags are added to the compiler command line after QMAKE_CXXFLAGS, and would re-enable that warning (because QMAKE_CXXFLAGS contains -Wall).
Answer: It sounds strange that you can't compile due to Qt library.
As I don't develop on Mac, what I would check is for supported Mac versions/compilers and how to compile on Mac. After that, if you fit requirements, I would report this as bug.

QT 4.8 Developing on Mac
[stackoverflow] How to build qt 5 project on mac

Another approach (as already reported in this QT-Bug: To #include  generates warnings) is to include pragmas around warned headers.
 #pragma GCC diagnostic ignored "-Wunused-private-field"
 #include <QtGui>
 #pragma GCC diagnostic warning "-Wunused-private-field"

Comment: gcc doesn't know about "-Wunused-private-field" and will warn with "unknown option after" this is a clang specific warning.
Comment: I didn't say I couldn't compile --- I just couldn't figure out how to eliminate a particular warning.
Comment: @David I misunderstood. It could help a pragma ignore.
Comment: There's something to be said for this approach so that the warnings will still be available for user code as opposed to library code though I hate to pollute my code with this stuff. However, since I've pulled down the entire source for Qt, I'm tempted to just remove the unused field myself!
Comment: clang supports gcc pragmas, that's why the code indicates GCC. But that does not mean this specific warning exists in GCC, it was an example. https://clang.llvm.org/docs/UsersManual.html#pragma-gcc-diagnostic
Answer: First of all I am not sure on points its bug of QT or not but I found one recent question on QT forum about same. I hope it is solved.
Possible bug: qmime.h warning "char type is unused"
There is one more,
Clang 4.2 warns about QMacMime unused private field "type"
This may help you.
Comment: These aren't bugs as far as I know --- I assume they're legitimate warnings for the Qt code but it's just a pity that the Qt folks haven't ensured that their code doesn't have such things as unused fields and other things that would cause warnings.
Answer: I'm not a clang guy, but according to http://clang.llvm.org/docs/UsersManual.html#controlling-diagnostics-in-system-headers you can use the -isystem flag with the directory in which those Qt headers are in, which will treat them as system includes and suppress warnings for them.
Comment: I tried adding    QMAKE_CXXFLAGS += -isystem-prefix /usr/local/Trolltech/Qt-4.8.6/include/ and
   QMAKE_CXXFLAGS += -isystem /usr/local/Trolltech/Qt-4.8.6/include/
but that didn't help.


Confused about hosting offer: 20 M/bit uplink speed vs Gig/E Uplink Connectivity?

Question: The datacenter in question is offering the following for colocating a server:

20 M/bit uplink speed
Gig/E Uplink Connectivity

Could someone explain the difference in the above? I'm confused as to what the throughput speed is for users who will visit websites hosted on this server.
Comment: Well, it would be 20Mbps. Why would you think that it would be 2Mbps?
Comment: Yes............
Comment: They're giving you a 1GbE physical connection which is capped at 20 Mbps of data transit.
Comment: @joeqwerty would that mean when website visitors download a file, the maximum speed would be 20mb/s or 2mb/s?
Comment: @joeqwerty I guess I'm confusing the bits vs bytes here. At 20Mbps the ability for users to download would only be 2.5 megabytes/second right?
Answer: The first 20 M/bit uplink is 20 Megabits, around 2.5 Megabyte per second.
The second is Gigabit thoughput is in the order of 125 Megabyte per second.
Measured from your server to the open internet, not including any congestion.
Small hosting companies may only have 1G or smaller backbones, while the largest hosts (AWS, Azure, Rackspace) have multiple carrier grade backbone circuits in the order of 200G+ scale.


Allowing access to subnets openvpn access server

Question: I have a centos server running a openvpn access server. On that server I am running a windows server in virtual box. On the centos server I am running the vpn with a network address 172.27.224.0 with 20 bits. The windows server is running a dchp server giving ip's of 192.168.1.0-200. When i try to connect to the widows shared folder from the vpn i can't using the name of the server but i can from the ip.
Answer: It seems like you are running a routed openVPN installation. In this configuration Netbios broadcasts are not forwarded via the VPN connection and you cannot connect using the Netbios name. See  http://openvpn.net/index.php/download/60-open-source/faq.html for details on what is forwarded in which configuration. You may also install a DNS Server on your windows server ( why do you run the DHCP on the virtual machine anyway? ) to resolve network names.
Comment: i have a dns server on the windows server


specify files in resources folder in spring application.properties file

Question: I have a Spring Boot application, the code need to access a file under resources folder. here is my application.properties file:
cert.file=classpath:/resources/cert.p12

however it always complained:
java.io.FileNotFoundException: classpath:/resources/cert.p12 (No such file or directory)

I double checked folder
my_project/target/classes
to make sure the file cert.p12 exits there.
and in the code I tried to access the file:
@Value("${cert.file}")
private String certFile;
....
@Bean
public Sender sender() {
    return new Sender(certFile);
}

what exactly is the this classpath? and why it cannot find the file? Thanks!
Comment: have you managed to solve this?
Comment: is there a solution for this?
Answer: Classpath includes what you have inside you resources dir.
Try:
cert.file=classpath:cert.p12

I'm assuming that you have standard maven catalog structure.
Comment: its threw the same error: FileNotFoundException: classpath:cert_key.p12.I use standard maven structure
Answer: This syntax doesn't work with a normal FileInputStream. Use the Spring Resourceloader instead.
@Autowired
private ResourceLoader resourceLoader;

@Value("${property.name}")
private String property;

File getPropertyFile(){
    return resourceLoader.getResource(property).getFile();
}

application.properties
property.name=classpath:filename.txt

Comment: when i run app with `java -jar` this code is not working.
Answer: You can just use XXX.class.getResourceAsStream("filename") to get a resource.
such as:
ObjectInputStream ois = new ObjectInputStream(MyClass.class.getResourceAsStream(PUBLIC_KEY_FILE));
        Key key = (Key) ois.readObject();
        ois.close();

And, this is work in my code.The MyClass is the class witch use your crt file. My PUBLIC_KEY_FILE is "/rsa/PublicKey" and just store at the src/main/resources/rsa folder
Answer: as @BeeNoisy said, you should use getResourceAsSreame(...) instead of getResource(...).getFile().
i see exactly your problem and my code ran in my computer correctly but when i load app with embedded tomcat with java -jar command i see this error:
so i change code like this and error resolved:
private final String licencePass;
private final String licenceName;

public ProcessFormController(@Value("${ramona.licence.keystore.fullname}") String licenceName,
                             @Value("${ramona.licence.pass}") String licencePass) throws Exception {
    this.licenceName = licenceName;
    this.licencePass = licencePass;
    this.restTemplate = new RestTemplate(getHttpsRequestFactory());
}

private ClientHttpRequestFactory getHttpsRequestFactory() throws Exception {
    logger.info("licenceName:" + licenceName);
    final InputStream resourceAsStream =
            getClass().getClassLoader().getResourceAsStream(
                    licenceName
            );
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    keyStore.load(resourceAsStream, licencePass.toCharArray());
    ...
}

properties:
ramona.licence.keystore.fullname=key.p12

Answer: Sharing my experience
Step 1 : Create your resource file lets say under /src/main/resources/data/test.data
Step 2 : Define the value in application.properties/yml
com.test.package.data=#{new org.springframework.core.io.ClassPathResource("/data/test.data").getFile().getAbsolutePath()}

Step 3 : Get the file in your code
@Value("${com.test.package.data}")
private String dataFile;

private void readResourceFile() {
   Path path = Paths.get(dataFile);
   List<String> allLines = Files.readAllLines(path);
}

Answer: This path worked for me
cert.file=./build/resources/main/cert.p12


How to find the limit $\lim_{x\to0}\frac{x\tan x-x\sin x}{x\sin^2x/\cos x}$

Question: Here is the limit I'm struggling with: $$\lim_{x\to0}\cfrac{x\tan x-x\sin x}{x\sin^2x/\cos x}.$$
Worked so hard to find it, but couldn't.
Comment: Use [this](http://en.wikipedia.org/wiki/L'H%C3%B4pital's_rule)
Comment: @Jlamprong No, way too complicated. Simplification of the expression yields $\frac{1-\cos x}{\sin x}$. That is hopefully known.
Comment: @DanielFischer: Yes, I just realized. I only saw $x$ appears before  $\tan x$.
Answer: Hint:  First notice that: $$\lim_{x\to0}\dfrac{x\tan x-x\sin x}{x\sin^2x/\cos x}=\lim_{x\to0}\dfrac{x(\tan x-\sin x)}{x\sin^2x/\cos x}=\require{cancel}\lim_{x\to0}\dfrac{\cancel x(\tan x-\sin x)}{\cancel x\sin^2x/\cos x}.$$
Then you can simplify it further as follows: $$\lim_{x\to0}\dfrac{\tan x-\sin x}{\sin^2x/\cos x}=\lim_{x\to0}\dfrac{\tan x-\sin x}{\sin x(\sin x/\cos x)}=\lim_{x\to0}\dfrac{\tan x-\tan x\cos x}{\sin x\tan x}.$$ Factor $\tan x$ and now try to identify expressions involving those two known limits: $$\lim_{x\to0}\dfrac{1-\cos x}x=0\quad\color{grey}{\rm and}\quad\lim_{x\to0}\dfrac{x}{\sin x}=1.$$
Answer: Simplify by $x\sin x$ and multiply numerator and denominator by $\cos x$ the limit becomes
$$\lim_{x\to0}\frac{1-\cos x}{\sin x}=\lim_{x\to0}\frac{x^2}{2 x}=0$$
Answer: Multiply top and bottom by $(\cos x) / x$:
$$\lim_{x\to0}\frac{\sin x-\sin x \cos x}{\sin^2x} = \lim_{x\to0}\frac{(\sin x)(1- \cos x)}{\sin^2x} = \lim_{x\to0}\frac{1- \cos x}{\sin x}$$
Now divide top and bottom by $x$:
$$=\lim_{x\to0}\frac{\frac{1- \cos x}{x}}{\frac{\sin x}{x}}$$
The limit of the top & bottom should be familiar to you:
$$\lim_{x\to0}\frac{\frac{1- \cos x}{x}}{\frac{\sin x}{x}} = \frac{0}{1} = 0$$
Answer: rewrite $\tan x = \frac{\sin x}{\cos x}$ and use the limit $\frac{\sin x }{x} \to_{x} 1$ and also $\lim_{x \to 0} \cos x  = 1$
Answer: I hope it's not too late...
$\dfrac{x\tan x - x\sin x}{\dfrac{x\sin ^2x}{\cos x}} \sim_0 \cos x⋅ \dfrac{x\left(x + \dfrac{x^3}{3}\right) - x\left(x - \dfrac{x^3}{6}\right)}{x\left(x^2 - \dfrac{x^4}{3}\right)} \sim_0 1⋅ \dfrac{3x}{6 - 2x^4} → 0$ as $x → 0$. The answer follows.


Let $A$ be an $n\times n$ matrix over real numbers such that $AB=BA,$ for all $n\times n$ matrices $B$

Question: I was thinking about the following problem:
Let $A$ be an $n\times n$ matrix over real numbers such that $AB=BA,$ for all $n\times n$ matrices $B$.Then which of the following options is correct?

(a)$A$ must be zero,
  (b)$A$ must be the identity,
  (c)$A$ must be a diagonal matrix,
  (d)$A$ must be either $0$ or the  identity.

I think the answer will be between $(c)$ and $(d)$. But i am not sure how to get the exact result.Can someone show me the right direction? Thanks in advance for your time.
Comment: Others have answered this question, correctly, as (c). But be careful. It is not true that if $A$ is a diagonal matrix, it has this property. It is only true for a specific subset of diagonal matrices.
Answer: You can immediately rule out answers (a), (b) and (d) by considering the matrix $A = 2I$, where $I$ is the identity matrix. This leaves (c) as the only option.
To actually prove statement (c), try looking at certain specific matrices $B$. For example, if $B$ is a matrix which has only one non-zero entry, what does the equation $AB=BA$ tell you about $A$?
Comment: thanks a lot .It is a very good approach for the multiple choice question like that.+1 from me.
Answer: Only (c) is correct. Just consider $n=2$ and $A=2I$. Then $AB=BA$ for all $2\times 2$ matrix $B$, but $A$ is neither zero nor identity.
Answer: Hint Let $B$ be a diagonal matrix with pairwise disjoint diagonal entries. Then $AB=BA$ implies that $A$ is a diagonal matrix. This is very easy to prove, just write explicitly $AB$ and $BA$.
P.S. The most general thing you can prove about this problem is that $AB=BA$ for all $B$ if and only if $A= cI$.


Shopify: List ONLY active tag

Question: I imagine someone has created this solution before and for the life of me I can't make sense of it.
I am using the following code to create a list of tags for my Men's T-Shirt department:

Garment Type

   {% assign tags = 'Short Sleeve, Long Sleeve, Polo, Crew %}
      {% for tag in tags %}
         {% if current_tags contains tag %}

{{ '-' | link_to_remove_tag: tag }} {{ tag }}

         {% elsif collection.all_tags contains tag %}

{{ tag | link_to_add_tag: tag }}

         {% endif %}
      {% endfor %}

It works as expected, but what I am trying to accomplish is if one of the tags is selected, say "Short Sleeve", then the list should display ONLY "- Short Sleeve" and nothing else. Not allowing the customer to select any other tags from that group. Simply because, if something is tagged "Short Sleeve" it is not "Long Sleeve"
As it is working now, the customer could select "Short Sleeve" and then select "Long Sleeve" resulting in no results.
Any guidance would be greatly appreciated, thanks!
Answer: The Filters page on the Shopify wiki states:

link_to_add_tag Links to products that have the given tag and any previously applied tags
link_to_tag Creates a link to the tag page

So, simply change link_to_add_tag to link_to_tag.
Also see:

Managing Subcategories using Tags. This article uses link_to_tag to filter products by colour.
Related discussion on Shopify forum, Only one Tag at a time.

Shopify: List ONLY active tag


Prove $I_n=\sum_{k=1}^{\lfloor{\frac{n+1}{2}}\rfloor}\frac{1}{(2k-1)^2}$

Question: Let $n\in\mathbb{N}$ such that $f_n(z)$ is a complex function series which is defined by:
$$f_n(z)=\frac 12\sum_{k=1}^{n}\cos(kiz)$$
For every $f_n(z)$ we will define the integral $I_n$ such that:
$$I_n=\int_\gamma zf_n(z)\ dz$$
When $\gamma(t)=\frac \pi 2(e^{-it}-1)$ such that $\ t\in\left[-\frac \pi 2, \frac \pi 2\right]$.
Prove that for every $n\in\mathbb{N}$, $I_n$ is given by:
$$I_n=\sum_{k=1}^{\lfloor{\frac{n+1}{2}}\rfloor}\frac{1}{(2k-1)^2}$$

When it comes to complex analysis I make efforts to solve the problems alone since I enjoy the challenges, but this one got me. I don't really know how to start.
Thanks!
Comment: Why not just substitute and integrate? What's the difficulty?
Comment: @metamorphy I didn't try that because I thought it would turn out to be long, and that there might be a trick to prove it in a more clever way... Do you suggest to do that anyway?
Answer: I figured it out: the given curve is half a circle, and it can be replaced by an easier curve (a segment on the imaginary axis) with the same start and end points because the given integrand is analytic. Replacing the curve and remembering that the order of integrating and summing can be replaced (as $n$ is finite) led me to the answer.


Rotating image also stretches or shrinks on iPhone

Question: I try to rotate my image :
UIImageView *image;
image.transform = CGAffineTransformMakeRotation(0.0175*degrees);
// 0.0175 = pi/180 = 1 degree in radians

if e.g
degrees = 90*x // x = 1,2,3,4

it's alright, but when degrees = 45 the image suddenly becomes really thin, and in other case it also stretches or shrinks.
What can be the cause of this?
I have also tried
CGAffineTransform transform=CGAffineTransformRotate(image.transform, degrees);
image.transform = transform;

with similar results.
EDIT: I have also tried with image.contentMode = UIViewContentModeScaleAspectFill; but then it gets to big
Comment: Dont use the transform.image it generally changes the dimensions of the image while rotating or zooming .... Can you provide the code in full instead of patches ?
Comment: The first code snippet is actually the full code.
Answer: Did you set bounds and center? Try  like this, but with your metrics:
    CGRect bounds = CGRectMake(0, 0, 20, 200);
    CGPoint center = CGPointMake(myrectr.origin.x + (bounds.size.width / 2.0f),
    imageViewRect.origin.y + (bounds.size.height / 2.0f) + 100.0f);

    [imageView setTransform:CGAffineTransformIdentity];

    [imageView setCenter:center];
    [imageView setBounds:bounds];

    [imageView setTransform:CGAffineTransformMakeRotation(M_PI / 4.0f)];

Comment: still i am getting the problem... is there any other option to do..PLease help me @Tutankhamen


How does mezzopiano relate to piano?

Question: I just came across the sonatas a quattro by Rossini in the Schott edition and in 2nd movement of first sonata directly follow three decrescendos:

from mf to p
from p to mp
from mp to pp

This clearly excludes a one-time typo and signals the assumption, that mp is softer than p while most references I found claim the opposite. Is this pecularity typical for a certain editor, nation or timeframe or just pure chance? Or is it the same phenomenon, that while everybody agrees what twice as fast means, twice as slow may be considered as faster or slower than slow?
Answer: "p" is always softer than "mp"

P = soft
mezzo = "half"
mezzo piano = "half soft"

In almost every circumstance what you have seen could be considered a simple editing error.  That said, if the intention was to diminuendo and then return to a "mp" marking or in fact grow from a previous "p" marking, then it would not be a typo.
I would recommend looking at different editions of the piece as well as giving it a listen to be absolutely sure.  If people are getting quiet and then staying quiet and all the other editions agree, then it's a typo.
Twice as slow is just a funny way of saying "half as fast".  It is akin to dividing a number by 2 or multiplying it by 1/2: both give the same result, but it's two different ways of expressing the same intent.
This is not the same as say, Andantino which will be slightly faster than Andante.
Comment: To add to this, all musical terms are in Italian, and the direct translations aren't always 100% accurate, so we say the next best thing.
Comment: @amandawitt - just to clarify, all *Italian* musical terms are written in Italian.  The French used French; Germans used German; etc etc.
Answer: I've always been taught to read mf and mp as abbreviations for "mezzo-forte" and "mezzo-piano" or "moderatamente piano" and "moderatamente forte".
Mezzo, in italian, means "half" and moderatamente means moderately (mildly, fairly). Both english and italian wikipedia page about this matter agree.

mp, standing for mezzo-piano, meaning "moderately soft".
mf, standing for mezzo-forte, meaning "moderately loud".

Given that, we can "rank" dynamic indications (from the softer to the louder) as follows:

ppp, pp, p, mp, (none), mf, f, ff, fff

so, as jjmusicnotes said, p is softer than mp and it could either be an error or a wanted effect.
Answer: The other answers are correct in that mp is always meant to be louder than p; that's simply the meaning of the term.
Regarding the Rossini specifically, it's interesting to note that he originally wrote the sonatas (at twelve years old, no less!) for two violins, cello, and double bass. Only later was it rearranged for a traditional string quartet and published. Additionally, it doesn't seem to be clear whether he did this later arrangement himself or not. He was known to have disliked the piece a great deal, and might have had nothing to do with it.
So it's entirely possible that those dynamic markings are not related to the original at all, and were instead an attempt by the editor to improve the piece - the only (later) edition I've seen doesn't contain anything of the sort, rather the movement is marked p as a whole with the occasional sf. If later editions follow the original manuscript (which was rediscovered, I believe, in the 1940s), it's possible that they are more accurate to the original, for whatever it's worth.
Still, either way I wouldn't throw out the possibility that it's meant precisely as it's written: piano, decrescendo, then immediately to mezzo-piano. That sort of indication isn't the most common but I've certainly seen it, especially in concert band music.

How does mezzopiano relate to piano?


Need help on adding options to $form via select field

Question: I altered the username field in login block into a select field and now I'm trying to filter the usernames by their user roles via another Select Field.
function design_form_alter(&$form, $form_state, $form_id){

    $users = entity_load('user');
    $user_names = array();
    $acc = array("PH","SL");
    $rolePH = array();
    $roleSL = array();
    foreach ($users as $user_id => $user) {
    $user_names[] = $user->name;
      if (in_array('PH', array_values($user->roles))) {
        $rolePH[] = $user->name;
      }
      elseif (in_array('SL', array_values($user->roles))) {
        $roleSL = $user->name;
      }
    }
    $user_arr = array_combine($user_names, $user_names);
    if($form_id=="user_login"){
    $form['roles']['#type'] = "select";
    $form['roles']['#weight'] = -0;
    $form['roles']['#size'] = 'auto';
    $form['roles']['#options'] = $acc;
    $form['roles']['#title'] = t('Role');
    $form['name']['#type'] = "select";
    $form['name']['#options'] = $user_arr;
    $form['name']['#required'] = true;
    $form['name']['#size']= 'auto';
    $form['name']['#title']= t('Organization');

    }
}

I'm a bit stuck, as you can see, I already separated users depending on their roles. My problem is how do I set the $form['name'] options when a role is selected. Right now I'm just showing all users in the DB.

Comment: What is `design_form`? Where does it come from? How does it look like when you `dpr($form)` or `var_dump($form)` at the beginning of your alter code? To help you with *how*, we need to know *what* we are working on.
Comment: design is the name of the theme I'm using and I think $form is a parameter of the method hook_form_alter.
Comment: you got the parameters right, but I'm asking what's in them. Also, logic like that should rather belong to module. Are you looking for [Form API AJAX](https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#ajax)? Last but not least: **are you altering all the forms now?** Because you are not testing if form ID means login form...
Comment: Tried var_dump($form) it just displayed an array looking like this http://pastie.org/9535700. Yes, I'm altering the form when its loaded in /user. I actually tested if($form_id=="user_login") its there.
Comment: Please post the actual code you are using, because now it's trimmed too much and misleading a bit. And have you read about Ajax and states in form api?
Answer: Borrowed From HERE:
If you want to do this hardcoded, you might try to use the #ajax property of the Form API

You can reload your second dropdown on change of the value of the first dropdown and change the value while reloading the form.

I made a little example to give you an idea :

$form['number'] = array(
  '#type' => 'select',
  '#title' => t('Select Number'),
  '#options' => array(
      0 => 1,
      1 => 2,
      2 => 3,
  ),
  '#default_value' => 0,
  '#ajax' => array(
    'callback' => 'ajax_replace_dropdown_default_value_callback',
    'wrapper' => 'wrapper-dropdown',
    'method' => 'replace',
    'effect' => 'fade',
  ),
);

$default_value = !empty($form_state['values']['number']) ? $form_state['values']['number'] : 0;

$form['open_closed'] = array(
  '#type' => 'select',
  '#title' => t('Open / Closed ?'),
  '#options' => array(
      0 => t('Open'),
      1 => t('Closed'),
      2 => t('Progress'),
  ),
  '#value' => $default_value,
  '#prefix' => '
',
  '#suffix' => '
',
);

function ajax_replace_dropdown_default_value_callback($form, $form_state) {
  return $form['open_closed'];
}

In your case you will have to do it in a hook_form_alter and add the #ajax property to your first dropdown and add prefix and suffix to give the second dropdown the proper value.

You can also check this link about AJAX with the FORM API :


Only allow further inheritance from child class

Question: Context: I'm doing some internal cleanup to move away from large & unwieldy data structures to more well-defined data structures.
Current
I have a class that does something like this:
class Base {
public:
  virtual int DoStuff(BigType input);
};

Calling code:
std::vector<Base*> bases;
BigType input;

for (const auto& base : bases) {
    base.DoStuff(input);
}

Child classes currently look like this:
class Child : public Base {
  int DoStuff(BigType input) const override {
    // do stuff
  }
};

Attempted
I added an intermediate interface:
template <typename SmallType>
class FocusedBase : public Base {
public:
  int DoStuff(BigType input) const override {
    return DoStuff(SmallType(input));
  }

  virtual int DoStuff(SmallType input);
};

Child classes now look like this. Note that SmallType may differ across child classes:
class Child : public FocusedBase<SmallType> {
  int DoStuff(SmallType input) {
    // do stuff
  }
};

Calling code remains the same.
Issue
I'd like to have new classes inherit from FocusedBase only, not Base. Any thoughts on how to do so?
Comment: fwiw, already your current code is broken due to object slicing. A `std::vector` can only store elements of type `Base`
Comment: @463035818_is_not_a_number I read this as hey want some way to make sure `class Child : public FocusedBase` is done instead of `class Child : public Base`
Comment: I have read the question, but it isnt perfectly clear why that is an "issue", because in your code `Child` does inherit from `FocusedBase` and not from `Base`. If Nathan is right, you want to disallow inheriting from `Base`.
Comment: whats wrong with the code? `FocusedBase` inherits from `Base` so it should be ok. Do you get a compiler error? Please post a [mcve]
Comment: @463035818_is_not_a_number I have "issue" explicitly bolded in the question. Also just realized the issue with the vector, what happens when I put together a contrived example.
Comment: If you change your `std::vector bases;` to `std::vector> bases;` user would have to use your intermediate class...
Comment: @Jarod42 The issue is SmallType differs across child types.
Comment: Shouldn't you remove `Base::DoStuff(BigType);` and provide instead `Base::DoStuff(SmallType1);`/`Base::DoStuff(BigType2);`?
Comment: Why not define you `Base` methods in `FocusedBase` directly and remove `Base` totally? I think a `Base` class that can not be further derived should not exist.
Comment: @Jarod42 see "calling code"
Comment: So calling code cannot(should not) change?
Comment: @Jarod42 You're proposing adding a new method to Base for each potential SmallType. That is not feasible because we don't know all the potential types. Since we need to iterate over a vector of objects with unknown types, there is no way to change calling code.
Answer: If you want to disallow inheriting from Base directly you can make Base::Base() private and make FocusedBase a friend:
struct Base {
    private:
    Base() = default;
    friend class FocusedBase;
};

struct FocusedBase : Base {};

struct Foo : Base {};

struct Bar : FocusedBase {};

int main() {
    //Foo f;  // error
    Bar b;  // ok
}


Is there a Radon-Nikodym derivative of a L^2-valued vector measure

Question: Let $\Omega$ be a measurable space and $X$ a separable dual Banach space. $X$ is known to have the Radon-Nikodym property: If $\mu$ is a $\sigma$-additive measure with range in $X$ and $\nu$ a $\sigma$-additive measure with range in $\mathbb{R}_+$ such that $\mu<<\nu$, then there exists some $\frac{d\mu}{d\nu}:\Omega\rightarrow X$ such that $\mu(E)=\int_E\frac{d\mu}{d\nu}d\nu$ (see theorem III.3.1 in "vector measures" by Diestel and Uhl).
I have an example that seem to contradict this result and I do not understand how:
Define $\Omega=[0,1],\ X=X^*=L^2[0,1],\ \mu(A)=\chi_A\ \forall A\subset\Omega$ the indicator function of $A$ (1 in $A$ and $0$ outside $A$) and $\nu$ the Lebesgue measure on $\Omega$.
If $\nu(A)=0$ then $\|\mu(A)\|_{L^2}=(\int_0^1|\chi_A|^2)^{\frac{1}{2}}=\nu(A)^{\frac{1}{2}}=0$ so $\mu<<\nu$. But I do not think there exists $\frac{d\mu}{d\nu}:\Omega\rightarrow X$, is there?

Why I think there is not: Assume there exists some
$\frac{d\mu}{d\nu}:\Omega\rightarrow X$ such that
$\mu(E)=\int_E\frac{d\mu}{d\nu}d\nu$ then for any $f\in X=X^*$ and
$E\subset\Omega$:
$$\int_Ef(\omega)d\omega=\left\langle\mu(E),f\right\rangle_{L^2}=\int_E\left\langle\frac{d\mu}{d\nu}(\omega),f\right\rangle_{L^2}d\omega=\int_E\int_{\Omega}\frac{d\mu}{d\nu}(\omega)(t)f(t)dtd\omega$$
which implies
$$\int_{\Omega}fd\delta_{\omega}=f(\omega)=\int_{\Omega}\frac{d\mu}{d\nu}(\omega)(t)f(t)dt$$ for all $f\in X$ and almost every $\omega\in\Omega$ which means
$\delta_{\omega}<<\nu$ which is not possible.
Comment: @copper.hat: $\mu$ is supposed to be a vector-valued measure, here taking values in the space $L^2[0,1]$.
Comment: So, for $\phi \in (L^2)^*$, we have $\phi ( \mu (A)) = \int_A \phi$? (identifying the dual here)?
Comment: @NateEldredge: Join my gang :-).
Comment: Are you using different $\sigma$-algebras for $\mu$ and $\nu$ - the Lebesgue algebra for $\mu$ and the full subset algebra for $\nu$?
Comment: An idea: Take a basis $\{b_\alpha\}$ for $L^2(\Omega)$ and let $\mu_\alpha(A)$ be the coefficient of $\mu(A)$ for $b_\alpha$. Then each $\mu_\alpha$ is a signed measure and there exists a function $\phi_\alpha$ such that $d\mu_\alpha = \phi_\alpha \, d\nu$. Thus $\phi = \sum_\alpha \phi_\alpha \, b_\alpha$ should satisfy $d\mu = \phi \, d\nu.$ But is $\phi$ a function?
Answer: You've left out a key phrase in your statement of the Radon-Nikodym property.  What is true is that if $\mu$ is a $\sigma$-additive measure of bounded variation with range in $X$ and $\nu$ a $\sigma$-additive measure with range in $\mathbb{R}_+$ such that $\mu<<\nu$, then there exists some $\frac{d\mu}{d\nu}:\Omega\rightarrow X$ such that $\mu(E)=\int_E\frac{d\mu}{d\nu}d\nu$.  (Check definition III.1.3 of Diestel and Uhl.)
Your measure $\mu$ does not have bounded variation.  Indeed, fix $n$ and let $A_i = [(i-1)/n, i/n) \subset [0,1]$, $i=1,\dots, n$.  Then $\|\mu(A_i)\|_{L^2} = n^{-1/2}$ for each $i$, so $\sum_{i=1}^n \|\mu(A_i)\| = n^{1/2}$, and the variation of $\mu$ is thus at least $n^{1/2}$; but $n$ was arbitrary.
Comment: @md2perpe: Well, I would think the correct generalization of $\sigma$-finite for a vector measure should be to require that we can write $\Omega = \bigcup_n \Omega_n$ where $\mu$ is of bounded variation on each $\Omega_n$.  The measure in this example doesn't satisfy that, either.
Comment: [Folland](https://www.amazon.com/Real-Analysis-Modern-Techniques-Applications/dp/0471317160) doesn't require bounded variation, only $\sigma$-finiteness of both measures. The measures are real-valued, however.


c++ strange syntax

Question: i dont understand some things in a code from a tutorial
first one: what is that comma "," doing in the middle there? is it mb a overloaded operator?
u32 TimeStamp = irrTimer->getTime(), DeltaTime = 0;

next i have a weird constructor from class CharacterDemo, why is there a ":" following some variables with weird brackets? im guesseing they are beeing initialized with the value in the brackets.. ?
CharacterDemo::CharacterDemo()
:
m_indexVertexArrays(0),
m_vertices(0),
m_cameraHeight(4.f),
m_minCameraDistance(3.f),
m_maxCameraDistance(10.f)
{
    m_character = 0;
    m_cameraPosition = btVector3(30,30,30);
}

im rly curiouse, explanation much appriciated
Comment: Hint: `u32` is a type. Also, http://stackoverflow.com/questions/1711990/what-is-this-weird-colon-member-syntax-in-the-constructor
Answer: It's an initialization list.
It calls the constructors of the members and parent classes of the specified class.
Note that you can only use it in the constructor of a class (because it only happens at its construction).
[edit] For your first question, it's a way to declare multiple variables of the same type at once. Note that it will not always work as expected : int * a, b will declare a variable a of type int *, and another variable b of type int (not a pointer).
Comment: +1 for mentioning the reason why this should be avoided in general, because too many people will not care to check up the details on how it works and quickly get confused.
Answer:
what is that comma "," doing in the middle there?

A statement like int i = 3, j = 4; is the same as int i = 3; int j = 4;
So, u32 TimeStamp = irrTimer->getTime(), DeltaTime = 0; is defining and initializing two variables of type u32: one named TimeStamp and the other named DeltaTime.

why is there a ":" following some variables with weird brackets? im guesseing they are being initialized with the value in the brackets.. ?

That's correct: google for c++ member initialization list.

c++ strange syntax


How to determine the pitch of the auxiliary note in an ornament

Question: I thought that the auxiliary note of a lower mordent (or other ornaments) was simply the note before in the scale unless the mordent had an accidental on top of it.  However, I ran into this discussion providing a much more complex rule explaining essentially that the auxiliary note should be a half-tone down unless the note played immediately before or after the mordent was a full tone below or when the mordent is applied to a 3rd or 7th.  Given that I never heard this before and that the full discussion leaves a lot of confusion as to how the accidental should be interpreted in that case, I am having doubts about that entire explanation.
Can someone explain simply what are the rules for playing the auxiliary note of lower (and upper) mordents, with and without accidentals?  Examples welcomed.
Thank you
Comment: AFAIK, you may choose yourself. It's either that, or I have been doing it right instinctively since I arrived at repertoire with mordents, as my teacher never objected.
Comment: I have done it instinctively myself as well for many years and my intuition is clashing with what I recently read in the pointer I provided. Hence my question. I am very much interested in knowing what the actual rule(s) is(are).
Answer: I got an answer to this question after talking to a few musicians.
The auxiliary note is determined by the melodic context.
For example, in D major, an auxiliary F and D should be raised.  Now, the trick is that there may very well be modulations so, for example, a piece starting in D major could turn into B minor, in which case the 7th (A) will likely be raised as it is typically in the minor classical scale.  I say "likely" because the song could be in minor but use a natural minor scale instead of the more common harmonic scale.  If that were the case, the A would not be raised.
In short, to a first approximation, one can just look at the alterations on the staff to know what auxiliary note to play and will be right most of the time, but to be sure, one should listen to play what is correct accordingly to the current melodic context.


Lipschitz condition normed vector space

Question: Am I right that $g: C^{1}[0,2],||*||_{C^1[0,2]} \rightarrow \mathbb{R}$ with $g(f)=f'(1)$ satisfies a Lipschitz condition?
Cause $|f'(1)-h'(1)|=|g(f)-g(h)|\le \text{max} |f-h|+ \text{max} |f'-h'|$, as the last term here contains already the lipschitz condition.
Answer: you are right: $$|g(f) - g(h)| = |f'(1) - h'(1)| \le \max_{[0,2]}|f'(x) - h'(x)| \le$$
$$\le \max_{[0,2]}|f'(x) - h'(x)| + \max_{[0,2]}|f(x) - h(x)| = \|f - g\|_{C^1},$$
then it is Lipschitz continuous with Lipschitz constant $L = 1$.

Lipschitz condition normed vector space


Alternating group index

Question: I am self-studying abstract algebra and Galois theory and I am not sure my understating is correct. I know that the Alternating subgroup $\mathbb{A}_n$ has index $2$ in the symmetric group $\mathbb{S}_n$ (the proof can be found in Herstein or Dummit & Foote).
Does that imply every element $\sigma\in\mathbb{S}_n$ can be expressed as $\sigma=\widetilde{\sigma}\alpha_{\sigma}$ where $\widetilde{\sigma}$ is any chosen fixed element in $\mathbb{S}_n$ and $\alpha_{\sigma}\in\mathbb{A}_n$ ?
Answer: No. If $\widetilde{\sigma}\in \mathbb{A}_n$ then clearly $\widetilde{\sigma}\alpha_\sigma\in\mathbb{A}_n$. On the other hand if $\widetilde{\sigma}\not\in \mathbb{A}_n$ then $\widetilde{\sigma}\alpha_\sigma\not\in\mathbb{A}_n$. It is a simple consequence of the fact that cosets partition whole group.
The correct claim is slightly different: if $\widetilde{\sigma}\not\in\mathbb{A}_n$ then every element $\sigma\in\mathbb{S}_n$ is either in $\mathbb{A}_n$ or $\sigma=\widetilde{\sigma}\alpha_\sigma$ for some $\alpha_\sigma\in\mathbb{A}_n$.

Alternating group index


Adding Zero to a column in first x rows in R

Question: I am creating a classification model for forecasting purposes. I have several ext files which I converted into one large list containing several lists (called comb). I then broke the large list into a separate dataframe with each list as its own column (called BI). Because each list may contain different number of elements, the simpler argument matrix(unlist(l), ncol=ncol) does not work. When reviewing alternatives, I made modification to compile the following:
max_length <- max(sapply(comb,length))

BI<-sapply(comb, function(x){
c(x, rep(0, max_length - length(x)))
})

This creates a dataframe assigning each list a column and assigning each missing element within that column a value of ZERO. Those zeros show at the end of that column but I would like them to be at the beginning of the column. Here is an example of current output:
cola colb colc
2    2    2
1    1    0
4    0    0

I need your help in converting my original code to produce the following format:
acola colb colc
2    0    0
1    2    0
4    1    2

Comment: Where is the original list `comb`?  That seems kinda important
Comment: what you want is to have all zeros, if any, "at the top" of every column? could you post with `dput` some of your list?
Comment: @VincentBonhomme & Hadd E. Nuff the dput is a large output but essentially comb is a list of 15 lists (all numeric, different number of elements, with numbers ranging from 0 to 18000).
Comment: @VincentBonhomme Yes to your question ('what you want is to have all zeros, if any, "at the top" of every column')
Answer: It might be sufficient to interchange the order in the concatenation c:
max_length <- max(sapply(comb, length))

BI <- sapply(comb, function(x){
    c(rep(0, max_length - length(x)), x)
})

EDIT: Based on additional information in the comments below, here's an approach that modifies the code in another way.  The idea is that as long as your first approach gives
you a proper data frame, we can circumvent the problem by using
the order-function.
max_length <- max(sapply(comb,length))

BI <- sapply(comb, function(x){
    .zeros <- rep(0, max_length - length(x))
    .rearange <- order(c(1:length(x), .zeros))
    c(x, .zeros)[.rearange]
})

I have tested that this code works upon a minor test example I
created, but I'm not certain that this example resembles your
comb...
If this revised approach doesn't work, then it's still possible
to first create the data frame with your original code, and
then reorder one column at the time.
Comment: But if we have a list, then I think we can use 'data.frame' upon it to create the desired result.
Comment: I had tried converting it into a dataframe but just did not mention it in my original response. I get this error `Error in data.frame(c(49.04, 48.7, 48.049997, 48.069997, 48.379999, 48.259999,  :
  arguments imply differing number of rows: 4666, 2686, 4431, 4627`. This differing number of rows is the same issue my original code tried to resolve so we are back at square one.
Comment: your edited version worked well. I have a few questions on what you did and I will spend some time now to try and figure it out. Thank you for your help.


UPnP and Port Forwarding with Lidgren fails

Question: I'm fairly new to networking and lidgren has made it much easier for me to begin adding multiplayer capability to my XNA PC game. I've been testing across the network setting up my laptop right next to me and it has been working great. The problem is I sent a copy of my game to a friend in the Netherlands and she cannot connect to me. I have it set up to where one person is the host and other people are clients who connect to that host.
The host sets up the server as follows:
<code> Config = new NetPeerConfiguration("game");
 Config.Port = 14242;
 Config.EnableUPnP = true;
 Config.MaximumConnections = 3;
 Config.EnableMessageType(NetIncomingMessageType.ConnectionApproval);
 Server = new NetServer(Config);
 Server.Start();
 Server.UPnP.ForwardPort(14242, "Forlorn Forest");
</code>
Here's the exception ForwardPort throws as it fails and gives "Bad Request":

And two web exceptions that are thrown:

It says something about the connection being closed by the remote host and unable to read data from the transport connection in the exception details:

Any thoughts as to what might be going on here? UPnP is enabled on my router. I've taken a look at network traffic with WireShark and I can see it display malformed packets though I didn't mess with any of the Lidgren code so I'm not sure why it would.
Comment: I've added a break point in "internal void ExtractServiceUrl(string resp)" and it gets to and sets the status to Available and then it goes to the method again a second time and that's when the exception occurs.
Comment: It looked like enabling UPnP had to set some stuff up so I decided to take out the ForwardPort request from there and put it in the host's update area and wait for UPnP to be set to available before I sent in the ForwardPort request and now I see it show up in the upnp portmap table on the router though it does still give the two exceptions and now after a minute or two it gives "The thread '' (0x149c) has exited with code 0 (0x0)".
Comment: After some looking into it, it could just be a thread created by Lidgren that concluded doing it's job. And maybe it's fine that I can't get rid of the exceptions... I see the port added to the UPnP portmap table so that's what's important I guess. I'll test again when I can.
Comment: I tested it with a friend who lives a few hours away and he was able to connect to me so perhaps it'll be alright to ignore those exceptions if it's working at least...
Answer: The UPnP protocol specification has unfortunately not been properly implemented on a huge number of the home routers out there. The effect of this is that all UPnP frameworks (Even the Intel spec framework) will fail to properly communicate UPnP with some local routers.
You should find that not all of your friends routers will successfully open the ports you request. The best you can do is make sure your code has no failure scenarios and uncaught exceptions relating to the UPnP framework you're using and that you have it well documented how users who fail UPnP can manually setup port forwards for your game.
Comment: Thanks for the explanation and advice. That's understandable. Many games seem to just leave it up to the players to be required to forward the port themselves. I'll try to do as you suggested and keep in mind that some people will be required to do it manually.


Is linear regression the best method for these data?

Question: Background: I'm looking at harbor seal weights by year to understand trends over time. Each year represents a distinct pupping season (May-July) so I treated year as a categorical variable to avoid seeing declines in seal populations in other months. Each individual is only measured once (not measuring same individuals year after year). I'm interested in describing the data rather than predicting. I fitted linear models as such:
model<-lm(weight~(as.factor(year)),data=seal)
This gives me an output of parameter estimates for each year, which is helpful in understanding trends over time. However parameter estimates are in reference to the intercept, 2005, which has no biological significance aside from being the first year of data collection.
My question is, did I perform the "best" test to help me understand trends over time? Or is there another  test that allows me to regress continuous data on a categorical variable without using any level as a reference? (Or if such a thing is illogical, and references are always required...)
Also, I've performed numerous t-tests to compare years, but I was curious if there was a method that compared >2 levels at once in absence of a reference.
Comment: for a descriptive analysis, why not plot seal weight, by year, using a box-and-whiskers plot?
Comment: Oops, I should have mentioned that I did make box-and-whiskers plots. The linear regression was an attempt to supplement that.
Answer: You have effectively run an ANOVA. If you want to see whether there are differences across years without the intercept, then you should just be able to wrap your fitted model in the anova() function like this: anova(model).
There's not going to be a right answer to this because what statistic you use ultimately is informed by what question you want answered. If you don't want to do prediction, then maybe framing things as a regression is not needed. If you don't care about differences between years but want to know trends, then ANOVA is probably not "correct". That ultimately is up to you and your research question, though.
I would just point out that I'm not sure that you can ignore any dependency from year to year. In other words, I think it's a hard sell to say that weights in 2006 are independent from weights in 2005. I get that you aren't measuring any of the same seals from year to year, but the seals still live in the same environment and are going to be impacted by that. The current method, to me at least, seems like a tough argument that years are totally independent from one another. If you are doing this at multiple sites, then you'd also probably want to be considering clustering and transition to a multilevel model. Similarly, there may be reason to think that there is a non-linear relationship between time and weight. For example, I would imagine that weights have some general (albeit soft) upper and lower limits for seals, and I can see how maybe an exponential function in time could help capture the dynamic nature of the ecosystem and weight. All this said, I'm 100% unfamiliar with modeling these kinds of things, so I wholly recognize that I could be barking up the wrong tree here. Just wanted to through out some of these thoughts because I think that modelling makes more sense when you're thinking about the data generation process (i.e., what potentially measurable things combined to give the data you have observed)
Comment: This is incredibly helpful. Thank you!


The 100 Coins Puzzle

Question: There are 10 sets of 10 coins. You know how much the coins should weigh. You know all the coins in one set of ten are exactly a hundredth of an ounce off, making the entire set of ten coins a tenth of an ounce off. You also know that all the other coins weight the correct amount. You are allowed to use an extremely accurate digital weighing machine only once.
How do you determine which set of 10 coins is faulty?
Answer: Assuming that all normal coins have a uniform weight:
I think you would want to number the sets $1,2,\ldots,10$. Then take $1$ coin from the first set, $2$ coins from the second set, $i$ coins from the $i$th set, and $10$ coins from the $10$th set. Then the weighing machine will display the correct weight minus $n$ hundredths of an ounce. Then the faulty set is the one from which you selected $n$ coins.
You could also do this by selecting $0,1,2,\ldots,9$ coins. I'm not sure if either strategy fails for any edge cases.
Answer: IF we take one coin=10 gram,and we take one from the first stack,two from the second stack,three coins from the third and so on until we pick up ten coins from the tenth stack.we are assuming all the coins are genuine and add like 10+20+30+40+50+60+70+80+90+100=550 grams
now if we we get total weight 551,we will sure that the fake stack is the first since one coins weight in the first stack is 11
if 552 then the second and so on to 563
Comment: Welcome to Math.SE. How is this answer different from the accepted answer ?.  Please refrain from answering old questions if you are not going to contribute anything new. It brings them un-necessarily to the top of some observable queue

The 100 Coins Puzzle


AASM transition from but except one state

Question: I have AASM with ActiveRecord model.
Have many statuses and events with their transitions.
I want to create event that will allow transition from any state except one.
event :set_vacant_pass do
  transitions to: :vacant_pass, from: ??
end

Answer: After some digging, i just decided to have simple solution:
event :set_vacant_pass do
  transitions to: :vacant_pass, from: Vacation.man_statuses.except('vacant_pass').keys
end

This will allow event transition from any state except vacant_pass.
(man_status is enum column and used for AASM)
Answer: Spitballing so syntax may not be perfect, but you can specify this explicitly using a list.  Supposing your valid states to transition to "vacant_pass" from are "new", "created" and "closed":
event :set_vacant_pass do
  transitions from: [:new, :created, :closed], to: :vacant_pass
end

Or you could use a guard
event :set_vacant_pass do
  transitions_from: Vacations.man_statuses.keys, to: :vacant_pass, guard: :transition_valid?
end

def transition_valid?
  self.state == :vacant_pass
end

Added extra, you can use
ClassName.aasm.states.map(&:name)

to get an array of symbols containing all possible states for your class.


How to make sample space of the following question

Question: My teacher gave me a question to solve.In the book of Ronald E. Walpole (Probability and Statistics for Engineers and Scientists), chapter no#3 exercise 1,question #2 which is as below:

3.2) An overseas shipment of 5 foreign automobiles contains 2 that have slight paint blemishes. If an agency receives 3 of these
  automobiles at random, list the elements of the sample space S, using
  the letters B and N for blemished and nonblemished, respectively; then
  to each sample point assign a value x of the random variable X
  representing the number of automobiles with paint blemishes purchased
  by the agency.

It means we have 2 DEFECTIVE AND 3 NON-DEFECTIVE automobiles;
But in the solution manual he makes samples as follows:
<code>Sample Space
NNN
NNB
NBN
BNN
NBB
BNB
BBN
BBB
</code>
but the question is how did he make the last sample {BBB}.I think it is not possible because we have maximum 2 blemished automobiles.and we are recieving 3 means repetition not allowed.Please tell me how {BBB} is possible.
Comment: A generous reading of the information is that two automobiles have been found *so far* to have blemishes (perhaps by means of sampling two autos out of the shipment).  This does not completely exclude the possibility that three, four, or even all five have blemishes.  (But this is a poor exercise regardless.  It could be made more useful by supposing the shipment is known to have (at least) three blemished cars, for then some of the unordered triples would be ruled out: NNN could not occur.)
Comment: Because this is a homework/self-study question, you should add the `self-study` tag to your question. See http://stats.stackexchange.com/tags/self-study/info
Answer: BBB would have been a possible sample if the simple random sample had been drawn with replacement.  In with-replacement simple random sampling, each selected item is "replaced" before the next draw is made. Each of the three draws is made from the original five, with probability of selection 1 in 5 at each draw.
This is a valid sampling method, but the description of the problem makes it clear that sampling was without replacement. I conclude that you are correct: A BBB sample point is impossible, and the listing in the solutions manual is in error.
Answer: As it is obvious, that we have two blemished cars, so it is not possible to select three from two,it is just anerror or a mistake by writer or publisher..


Jenkins cannot clone repo from gerrit over http

Question: I'm getting an error while trying to clone repo from gerrit with my jenkins user.
I have a jenkins user in gerrit with set ssh key and http password. I can login with password to gerrit UI but when I try to clone repo over http I'm getting fatal: authentication failed.
I'm using nginx and here is my configuration for both sites
Here is nginx configuration for gerrit
upstream gerrit {
    server localhost:8092 fail_timeout=0;
}

 server {
    listen 80;
    server_name gerrit.domain.com;
    return 301 https://$host$request_uri;
 }

 server {
    listen 443 ssl;
    server_name gerrit.domain.com www.gerrit.domain.com;

    proxy_ssl_session_reuse off;

    ssl_certificate
    /etc/letsencrypt/live/gerrit.domain.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key
    /etc/letsencrypt/live/gerrit.domain.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot

    if ($scheme != "https") {
       return 301 https://$host$request_uri;
    } # managed by Certbot

    location / {
       allow 10.8.0.0/24;
       deny all;
       proxy_set_header        Host $host:$server_port;
       proxy_set_header        X-Real-IP $remote_addr;
       proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
       proxy_set_header        X-Forwarded-Proto $scheme;
       proxy_set_header Connection "";
       proxy_set_header Authorization $http_authorization;
       proxy_pass_header  Authorization;
       proxy_redirect http:// https://;
       proxy_pass              http://gerrit;
       proxy_http_version 1.1;
       proxy_request_buffering off;
       proxy_buffering off; # Required for HTTP-based CLI to work over SSL

       auth_basic "Restricted";
       auth_basic_user_file /etc/nginx/.htpasswd;
 }

and nginx configuration for jenkins
upstream jenkins {
    server localhost:8080 fail_timeout=0;
}

server {
    listen 80;
    server_name jenkins.domain.com;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl;
    server_name jenkins.domain.com www.jenkins.domain.com;

    ssl_certificate /etc/letsencrypt/live/jenkins.domain.com-0001/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/jenkins.domain.com-0001/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot

    proxy_ssl_session_reuse off;

    if ($scheme != "https") {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    location / {
        allow 10.8.0.0/24;
        deny all;
        proxy_set_header        Host $host:$server_port;
        proxy_set_header        X-Real-IP $remote_addr;
        proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header        X-Forwarded-Proto $scheme;
        proxy_set_header Connection "";
        proxy_redirect http:// https://;
        proxy_pass              http://jenkins;
        proxy_http_version 1.1;
        proxy_request_buffering off;
        proxy_buffering off; # Required for HTTP-based CLI to work over SSL
        add_header 'X-SSH-Endpoint' 'jenkins.domain.com:50022' always;
        proxy_read_timeout 150;
    }
    location = /favicon.ico {
        log_not_found off;
    }
}

I have tried using password which is stored in /etc/nginx/.htpasswd and the one which I've generated in gerrit UI for jenkins user but both are not working.
Does anyone have an idea why it doesn't work?
Additionally in nginx error.log I can see "user "jenkins": password mismatch" error. But with same password I can login to gerrit UI.
Answer: I have found out that after removing
auth_basic "Restricted";
auth_basic_user_file /etc/nginx/.htpasswd;

lines from gerrit nginx configuration jenkins is able to clone repo, but after that I'm getting error from website that http authentication was not setup propertly.
Answer: I would increase the fail timeout from 0 as logic tells me that gives you exactly 0 seconds before timeout and fail.


Executing JavaScript in pure Python environment

Question: I want to run existing simple (no special tricks) JavaScript code (several thousand lines) in a pure Python environment (Google AppEngine).
The code runs fine with PyV8 (but it is not pure Python).
Is PyJON mature enough for this?
Can I define custom objects in Python and use them in JavaScript (like in PyV8)?
Comment: I'm not aware on any Python library that does that. I would probably setup some external service (aws?) with an API to do that. Your code can call the api and get the result.
Comment: The only way to know if PyJON is mature enough is to give it a try.  And if that doesn't work, lazy1 has a good suggestion.
Comment: @lazy1: This (AWS) was the original idea. But the system would be much simpler, if the JavaScript could be run on the AppEngine backends, where the data store can be accessed  and where someone else is responsible for the system wnbironment.
Comment: @Theron: OK, I will do just this. I have already implemented my first Python object and I am able to access it from JavaScript. It is a bit different from PyV8, but i seems to work.
Answer: You can use gae-init, where you can access you datastore objects in JSON format.


WordPress: Use shortcode_atts in other function

Question: Is it possible to use variables from shortcode_atts in another function? Here is my idea:
Posting
[gallery ids="1,2,3,...n"]
Function get_gallery_ids()
//get the gallery-ID's from post
function get_gallery_ids($atts) {
extract(shortcode_atts(array(
'ids'   => ''
), $atts));
return $ids;
}

Function explode_ids()
//example function with ids
function explode_ids($ids) {
$ids = explode(',' $ids);
}

How do I implement it? The return just echos.
Update
The code above is a part of my own new gallery_shortcode.
remove_shortcode('gallery', 'gallery_shortcode');
add_shortcode('gallery', 'get_gallery_ids');

Comment: Are you rewriting the *gallery* shortcode? Is `get_gallery_ids` the callback of your shortcode? I suppose you'll have to dig into WP [`shortcodes.php`](http://core.trac.wordpress.org/browser/tags/3.6/wp-includes/shortcodes.php) file and tweak some of its functions to your own.
Comment: Thank you, and yes, I'm rewriting the gallery shortcode. I went through the code, but WordPress saves their return in §output . = value. ... $output . = "" ... return $output;
Is there no better way?
Comment: Research at [wordpress.se], check this results: http://wordpress.stackexchange.com/search?tab=votes&q=gallery%20shortcode%20is%3aq
Comment: It helped. Thank you! I researched and somebody had a similar problem and the answer was solved by a link back to stackoverflow. Funny!
This helped me: http://stackoverflow.com/questions/14277794/wordpress-3-5-own-gallery-with-included-images-doesnt-work
Answer: I have an Idea:
I use examples from the WordPress Codex
http://codex.wordpress.org/Shortcode_API
function bartag_func( $atts ) {
    global $post;   // this is new
    extract( shortcode_atts( array(
    'foo' => 'something',
    'bar' => 'something else',
), $atts ) );
    update_post_meta($post->ID, "gallery_used_atts", $atts); // this is new

return "foo = {$foo}";
}
add_shortcode( 'bartag', 'bartag_func' );

now you are able to get the $atts you are using on a specific post or page by
$att_values = get_post_meta( $post_id, "gallery_used_atts", true );

and then you can use them for whatever you want.


How to set max file descriptors for a container?

Question: I want to run elasticsearch in a container (namely nspawn) and it requires the number of max file descriptors to be higher than the default 1024.
This is done, in the container, in the systemd service file appropriate for elasticsearch. This request upon service start is however not taken into account, the limit stays at 1024.
I then tried to change this limit on the command line within the container but I believe this is not possible (which is understandable):
root@elk:/etc/elasticsearch# ulimit -n 65536
-bash: ulimit: open files: cannot modify limit: Operation not permitted

I believe that this limit should be either set, or allowed to be set, at the host level. Where should I set this up?
Answer: A bug report for systemd gave the solution. One needs to create or update /etc/systemd/system/systemd-nspawn@.service.d/ulimit.conf and add  LimitNOFILE=infinity in the [Service] section:
mkdir -p /etc/systemd/system/systemd-nspawn@.service.d/
cat <<'EOF' >/etc/systemd/system/systemd-nspawn@.service.d/ulimit.conf
[Service]
LimitNOFILE=infinity
EOF
systemctl daemon-reload
systemctl stop systemd-nspawn@CONTAINER
systemctl start systemd-nspawn@CONTAINER


Where Mysql procurar por palavra completa

Question: Eu tenho um banco de dados e gostaria de saber como eu faço pra procurar pelo dado digitando o resultado completo usando where
Exemplo:
ID  NOME  CODIGOS
1  | Joao   | 9714,51,100
2  | Maria  | 50,9714,88100

Ai queria fazer que retornasse um where pesquisando por CODIGOS
Pesquisa: 100
Mostrar: Joao
Pesquisa: 9714
Mostrar: Joao, Maria
Eu fiz assim:
SELECT * FROM usuarios WHERE codigo like '%100%'

Porém o 100 pesquisado ta mostrando todos os resultados que tem 100, então retorna 88100 e 100
O que posso estar fazendo?
Comment: se uma resposta lhe serviu então marque-a como aceita, veja como e porque em https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-resposta/6985#6985
Answer: FIND_IN_SET - Serve para localizar dados em um campo da tabela que tenha valores separados por vírgula.
SELECT * FROM nomeTabela WHERE FIND_IN_SET('valorBuscado', nomeColuna);

Exemplo tabela usada:

SELECT * FROM usuarios WHERE FIND_IN_SET(100, codigo);

Resultado
Comment: Faltou verificar se o resultado de `FIND_IN_SET` e maior que 0 (zero), pois essa função apenas retorna o indice da string *9714* na string de valores separados por virgula. Ficaria `where FIND_IN_SET('9714', nomeColuna) > 0;`
Comment: Nice! Vai um teste ai para complementar.... http://sqlfiddle.com/#!9/9760cf/14
Comment: Funcionou certinho, obg.. não conhecia essa função find_in_set
Comment: @RodrigoK.B não é necessário, se o resultado for `0` ele funcionará como o `false` e se for diferente funcionará como o `true`.
Comment: @LucasMoraes, já que resolveu, marca a resposta como aceita ;)


jQuery: append a templated box with some inner html

Question: Sorry if my title is not clear, I'm not sure how to word this.
I'm new to jQuery, and here is what I am trying to do.
I want to show one or more announcement boxes on top of the webpage.
Let's say I have some kind of template "div" element with a class name, some html to make it into a pretty box. And a placeholder or something, where the actual message (html) will be.
Then I would use $.append to insert each of this boxes on my page, specifying the custom message for that box.
My problem is, how can I create such a DIV template and how can I add content to it?
I hope this is clear ...
Answer: You could create a helper function like this:
$.messageDiv = function(message, style){
    var $div = $('
').addClass('message-div message-style-' + style);
    var $message = $('
').appendTo($div);

    $message.html(message); // Or use .text() if message contains no HTML or if should be escaped if it does contain HTML
    return $div;
}

And then use it to add the message to the page:
$('#content').prepend($.messageDiv('My Cool Message!', 'warning'));

And it would create and prepend (Added to the inside top of #content) this markup:

Your text here


MathML support in Adobe Digital Editons for EPUB

Question: I am using MathPlayer to render MathML in an XML file. I am creating an EPUB. The ebook reader which I am using is Adobe Digital Editions. But it is not rendering the mathematical equations properly. Does ADE support MathML? Is there a way to do it?
Comment: I don't think ADE comes anywhere near supporting MathML. The practical way to write an e-book with lots of math in it is to create it in PDF format.
Answer: ADE doesn't support MathML. If you are dependent on using ADE, your best bet is to use PNG graphics in your EPUB. This will enable your EPUB + Math to work on many more readers, since MathML is not well supported either inside or outside the browsers.
Some EPUB readers have incorporated the MathJax javascript library into their implementations. You can see which readers have MathJax support here: http://www.mathjax.org/resources/epub-readers/
Hope this helps.
Best regards,
Jean K.
Comment: FWIW, we're in the midst of updating the EPUB 3 support grid. We're working with the IDPF conformance test suite and testing is underway right now. The new conformance test suite will definitively answer questions of support that were previously left up to vendor specifications and crowdsourced information. That said, I think it is doubtful that the actual Adobe Digital Editions will natively support MathML any time soon. Maybe we should convince them to install MathJax! ;)
Comment: Always useful to confirm: http://www.bisg.org/what-we-do-12-152-epub-30-support-grid.php


Django: reverse(view_function) does raises NoReverseMatch

Question: Reversing by view-name works, and reversing by view-method, too.
But if the URLs use a prefix reversing by view-method does not work. At least in my case.
Old code
url=reverse('myapp:foo-view')

New code. Both versions don't work
url=reverse(foo_view)

url=reverse(foo_view, prefix='myapp')

Again, reversing by view-method works perfectly if the URLs have no prefix.
Background: Jumping to the matching source code with an IDE is fun.
Comment: Strange, I use extensively what you refer to as 'old code', why exactly isn't working?
Comment: Path on string will be deprecated, but  I have not news about import string will be removed. Why do you say that?
Comment: Where did you read that reversing like that is deprecated? Certainly using strings in a urlpattern is deprecated, but I don't recall hearing the same about reversing.
Comment: https://docs.djangoproject.com/en/1.8/internals/deprecation/ The ability to reverse() URLs using a dotted Python path will be removed. The example uses a named pattern. This won't be deprecated. I changed the question since the deprecation of dotted paths is not relevant in this context.
Comment: Show us your url configuration. At the very least, you're misusing the name 'prefix'. The `myapp` in `myapp:foo-view` is a namespace, and reversing a namespaced url by the view function itself is not supported.
Comment: @knbk your hint "reversing a namespaced url by the view function itself is not supported" was good. I found this issue: https://code.djangoproject.com/ticket/17914. My question is solved now. If you want to, you can write an answer. Thank you!
Answer: reverse() does not support namespaced view references
https://code.djangoproject.com/ticket/17914


How can I save two logos for a custom theme?

Question: I need to save two custom logos in a custom theme and use them on the site. Can I somehow create a custom field in theme settings or maybe save the path to another logo in one of the .yml theme files?
Answer: Created theme-settings.php in custom theme root, there created new function, it renders new fieldset and a managed_file field
function theme_name_form_system_theme_settings_alter(array &$form, FormStateInterface $form_state) {
  $form['options_settings'] = [
    '#type' => 'fieldset',
    '#title' => t('Theme Specific Settings'),
  ];

  $form['options_settings']['add_logo'] = [
    '#type' => 'managed_file',
    '#title' => t('Additional logo'),
    '#upload_location' => 'public://logo/',
    '#default_value' => theme_get_setting('add_logo'),
    '#states' => [
      'visible' => [
        ':input[name="File_type"]' => ['value' => t('Upload Your File')],
      ],
    ],
  ];
}


What's a good library or coding approach to create an XML-like file at run time

Question: I would like to write some sort of API such that I can call it and say hey add this thing as the subclass of that thing and the output File that it generates for me I would able to see something like this:

or tell it to declare these things as a class and the output look would look like this:

In here, just those Person and Student are the params that I will pass to the API. The rest of it are like keywords, will always be the same.
Basically something like this: http://www.w3.org/TR/owl-ref/#subClassOf-def
So I am interested to know about your suggestions for what is good approcahc or Libaries, etc... that help me with this sort of file manipulation?
Thanks.
Comment: Have you tried searching for a library that will suit your needs? Where did you look? What have you found that came close?
Comment: And why can't you use xml?????
Comment: @TonyHopkinson : That's part of the question: Do you think using XML methods is a good option to do this or there are better ways? If yes, then like what?
Comment: It is? Of course it's a good option. It's there, it's standard and it's proven. No need to for you or anyone else to invent a subtly different flavour of mark up.
Answer: You could use c# and use the XmlDocument class
Basically you specify what nodes to add to an XML document by using it's methods, then you can grab the XML output and stream it to a file etc
http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.aspx
What experience have you got with programming?
Example of usage here:
http://msdn.microsoft.com/en-us/library/fw1ys7w6.aspx
I suppose it depends on what kind of control you need - this may be overkill for what you want