Linear Algebra: abstract/general vector space (Determinant space) Dimension theorem

Question: I have this linear algebra question
Note the transformation $T:\mathbb{R}^2 \rightarrow \mathbb{R}$
\begin{equation}
T(x_1,x_2) = \det\begin{bmatrix} x_1 & x_2 \\ -5 & 5 \end{bmatrix}\\
\end{equation}
So for this transformation we need to find the kernel and verify the Rank-Nullity Theorem.
So far, I can choose values of $x_1$ and $x_2$ to get the determinant to be zero.
So from determinant we would get:
$x_1\cdot5 - (-5)\cdot x_2 = 0$
$5x_1+5x_2 = 0$
And cleaning this up, we get:
$x_1 = -x_2$
So the vectors in the kernel form this vector:
$$
(x_1,x_2) = (x_1,-x_1) = x_1(1,-1)
$$
So we have this parameterized solution using $x_1$ as a parameter.
So this I believe is 1-dimensional. So Nullity = 1.
But how to get the rank and with the dimension of the domain, not too sure.
Answer: Hint: Everything you have done is fine, now use the rank-nullity theorem
Comment: OK, my question is, since the domain space of T is $R^2$, does that mean that dim(V) = 2.
Comment: So from the equation  of rank-nullity theorem we would have: Rank(T) + Nullity(T) = dim(V), hence Rank(T) = dim(V) - Nullity(T) = 2 -1 = 1?
Comment: Yes, that's basically it.
Comment: Ok, so based on the definition of T:V->W, I guess that we always are given the dimensions of V and W in general then?
Comment: The dimension of $W$ is actually not used in the theorem. But yes, the dimension of $V$ is relevant and needed
Comment: OK, that is one part of the puzzle i needed to know then, that was kind of holding me back. Thanks again 'b00n heT', really appreciate your input. I will give you as the correct answer to this question.
Comment: you are welcome Palu!


Prove that $NP = NQ$.

Question:

$M$ is the orthocenter of $\triangle ABC$. $D$ is a point outside of $\triangle ABC$ such that $\widehat{ABD} = \widehat{DBC} = \widehat{DMC}$. $N$ is the orthocenter of $\triangle BCD$. Let $P$ and $Q$ respectively be the circumcenters of $\triangle ABC$ and $\triangle DAB$. Prove that $NP = NQ$.

I tried to let $R$ be the circumcenter of $\triangle BCD$ and prove that $\triangle BRM = \triangle BNQ$. But I still don't know how.
Comment: I thought the correct statement was that $P=NP$ ...
Comment: You seem to ask many interesting question like [this one](https://math.stackexchange.com/q/3232979/81595), where do you get them from? $MBCD$ is an inscribed quadrilateral if that helps anyhow.
Answer: Let us draw some more points that may be or not relevant for the solution.
(My way to solve synthetic geometry problems is not to restrict to the problem as target, but rather to understand all geometrical relations / connections in the given situation.)
In the following picture...

the points were constructed in the following order.

We start with the $\Delta ABC$.
We draw the circumcircle $(ABC)$, and mark with $P$ its center. $P$ was constructed as the intersection of the side bisectors, drawn in green. Among them, the side bisector for the side $AB$ is the more interesting one, since soon we will need the center of an other circle through $A,B$.
$M$ is the orthocenter of $\Delta ABC$, the intersection of the heights, and in the picture we also have on two of the heights, the ones from $B,C$, the points $B_1\in AC$, $C_1\in AB$ on the opposite sides, and also $B_2,C_2$, where the heights intersect the circle $(ABC)$.
Note that (in measure) $\widehat{B_1MC_1}=\pi-\hat A$, since $\widehat{B_1MC_1}$ and $\hat A=\widehat{BAC}$ are opposite angles in the concyclic $AB_1MC_1$. (Or just drop from $2\pi$ the two right angles in $B_1,C_1$.)
Let $BB*$ be the angle bisector of the angle in $B$ in $\Delta ABC$, the point $B^*$ being on the circumscribed circle $(ABC)$ of $\Delta ABC$. The arc $\overset\frown{AC}$ (of length $2\hat B$) is thus cut in two equal parts by $B^*$.
Now we construct $D$ as in the problem, insuring that $\widehat DMC$ is half $\hat B$. In particular, $\angle CMD=\angle CBD$ implies $BCDM$ concyclic. This implies also
$$
\widehat{BMC}=
\widehat{BDC}\ .
$$
(So $D$ can be alternatively constructed as the intersection of angle bisector $BB^*$ with the circle $BMC$.)
Let now $N$ be the orthocenter of $BDC$. With the same argument as above, showing that the angles
$\widehat BAC$ and
$\widehat BMC$ add to $\pi$, we also get that
$\widehat BDC$ and
$\widehat BNC$ add to $\pi$. In particular:
$$
\widehat BAC
=\pi-\widehat BMC
=\pi-\widehat BDC
=\widehat BNC\ ,
$$
so $N$ is also on $(ABC)$ and we have
$$
PA=PB=PC=PN\ .
$$
Where on the circle $(ABC)$ is more exactly positioned $N$? (So that we possibly get rid of the definition of $N$ using the complicated point $D$...) We show that $N$ is on the angle bisector of $\angle DCB^*$, and then compute explicitly the angle $\angle NBB^*$, so that $D$ is no longer needed as intermediary station to define $N$. For this, let us compute the angle $\angle NCD$...
$$
\begin{aligned}
\widehat{NCD}
&=
\frac\pi2-\widehat{B^*DC}
\\
&=
\frac\pi2-(\pi-\widehat{BDC})
=
\frac\pi2-(\pi-\widehat{BMC})
\\
&=
\frac\pi2-\hat A\ ,\qquad\text{ and we compare with}\\
\widehat{B^*CD}
&=
\widehat{B^*CB}
-
\widehat{DCB}
\ ,\qquad\text{ so let us compute the last angle first}\\
\widehat{DCB}
&=\pi -
\widehat{DMB}
\\
&=\pi
-
\widehat{DMc}
-
\widehat{CMB}
\\
&=\pi
-
\frac 12 \hat  B
-
(\pi-\hat A)
\\
&=
\hat A
-
\frac 12 \hat  B\ ,\qquad\text{so}
\\
\widehat{B^*CD}
&=
\widehat{B^*CB}
-
\widehat{DCB}
\\
&=
\left(
\hat C +\frac 12\hat B
\right)
-
\left(
\hat A
-
\frac 12 \hat  B\right)
\\
&=\hat B+\hat C -\hat A
\\
&=\pi -2\hat A
\\
&=2\widehat{NCD}\ .
\end{aligned}
$$
So $CN$ is the angle bisector of $\angle DCB^*$, which means we have the measure of $\overset \frown {NB^*}$ by considering (double of the) inscribed angles:
$$
\widehat{NCB^*}
=
\widehat{DCN}
=
\frac\pi 2-\hat A
=
\widehat{ABB_2}
=
\widehat{ACC_2}
\ ,
$$
so
$$
\overset \frown{B^*N}=
\overset \frown{B_2A}=
\overset \frown{AC_2}\ ,
$$
$$
B^*N=
B_2A=
AC_2\ ,
$$
and
this gives a construction of $N$, which is independent of $D$.
Observation: $B^*$ is the half point on the arc from $A$ to $C$, so $PB^*$ is the side bisector of $AC$. Then
$$
\widehat{NPB^*}
=
\operatorname{measure}(\overset\frown{NB^*})
=
\frac 12
\operatorname{measure}(\overset\frown{C_2AB_2})
\widehat{C_2BB_2}
\ ,
$$
and because of $BB_2\|PB^*$ we get $PN\| BC_2$.
Note that from $
\overset\frown{C_2N}
=\overset\frown{AB^*}
=\overset\frown{B^*C}
$, we get $NB^*\|CC2\|PQ$,
where $PQ$ is the side bisector of $AB$,
where $Q$ is the center of thew circle $(ABD)$, chosen by my hand on the side bisector for its reference, since we finally have to add it into the picture.
We have now everything but (details on) $Q$. Time to attack the point $Q$.
(Try to stop here and find the own proof starting with the above information.)
I will take a break here and insert some details (which are not important for the rest of the proof), just to not divulgate the idea in the very next line.

This is the break, the intermezzo. Observations without proof.
The angle in $M$ between $CM$ and the prolongation of $AM$ is equal to $\angle
AMC_1=\hat B$, so i also filled in an unneeded complication, the bisector of this angle. Then we have in $M$ three angles equal to $\frac12 \hat B$, so it is natural to draw all three of them. For this, consider the reflection $D'$ of $D$ w.r.t. $MC$. Then the three equal angles are between the prolongation of $AN$, then $MD'$, $MC$, $MD$. And the point $D'$ is on the side bisector $PB^*$!

Let us finally show $QP=NB^*$ by considering the projections of these segments, placed on parallel lines, onto the bisector $BB^*$.
The projections of $Q,P$ on it are respectively the midpoints of $BD$, and respectively $BB^*$, so the length of the $PQ$-projected segment is $\frac 12(B^*B-DB)=\frac 12B^*D$, which is also the projection of $NB*$. From $QP$ parallel and equal $NB^*$ we get $PQNB^*$ parallelogram, so $QN=PB^*=PN$.

$\square$
Answer: Here is another solution which came from "mirror circle"

if circle O is $\triangle ABC $ circum, H is the orthocenter, then the circle O' which pass H,B,C will be the mirror circle of BC with same radius. M is the midpoint of BC, we have $ AH=2OM=OO'$ . and if a  $\triangle A'BC $ is on circle O', then the orthocenter H' must on circle O and  $ A'H'=2O'M=OO'$

since the proof is very simple, I don't give details here.
2.
solution:
let circle R' is the mirror circle of circle R, connect $RR',OR'$, extend $BD$ to circle R at point $E$, connect $NE$,$NC$,
it is trivial $\angle NEB= \angle NCB $, $N$ is orthocenter $\implies NC\perp BD \implies \angle NEB + \angle DBC =\dfrac{\pi}{2}=\angle NEB+\angle EBA \implies NE \perp AB $
$\angle NDE= \angle BDF, \angle BDF+\angle DBC =\dfrac{\pi}{2} \implies \angle NDE= \angle NED \implies ND=NE=AM=RR'$
$ AB $ on circle $O$ & circle $R \implies OR \perp AB $
with same reason, $OR'\perp BD, RR'\perp BC \implies \angle ROR'= \angle ABD ,\angle RR'O= \angle DBC  \implies RR'=OR=NE ,OR // NE \implies NO=ER$
it is trivial $NR=ER$ (radius) $\implies NO=NR$
Comment: OK, let us compare with "the other proof" (TOP), which takes its time to show that $N$ is on the circle $(ABC)$, and shows the paralelogram $NDMA$. This is 1 above and it is assumed it is so (because it has a name and is simple). Then the proof highly depends on the point $E$, in "the other proof" it is $B^*$. The proof shows first $NE\perp AB$. This is also contained in TOP. The point $R$ is not defined, but i suppose the idea is also to show $NQPE$ parallelogram. Same proof, but using shorter arguments. (Taking time to define all objects makes the proof readable, but slightly longer.)

Prove that $NP = NQ$.


$\sqrt{180\mathbb Z} = 30\mathbb Z$, $(180\mathbb Z:700\mathbb Z)= 9\mathbb Z$

Question: (First time studying rings, and I need some help on this example about radical ideal and fraction ideal)
Let $\sqrt{I}$ be the radical ideal on the commutative ring $R$, defined as $\sqrt{I}=\{r\in R: r^n\in I\ \mathrm{for\ some\ } n\in\mathbb{Z}^{+}\}$.
Then, for example, $\sqrt{180\mathbb Z} = 30\mathbb Z$, since $180=2^23^25$, and $30 = 2*3*5$.
Using this example, I can now solve any similar problem, but I do not understand why this method of prime factorization works.
I was also confused about the example regarding a fraction ideal.
$(I:J)=\{x\in R:xJ\subseteq I\}$, where $I, J$ are ideals in $R$.
The example that was given to me was this:
$(180\mathbb Z:700\mathbb Z)= 9\mathbb Z$.
The method to obtain this is as follows: $180=2^23^25, 700 = 2^25^27$.
And we see that
$180/gcd(180, 700) = 9$.
I feel like once I see the answer it'll be clear, but as of now I do not see it.
Answer: The key fact for the first question is this:

If $p$ is prime and $p$ divides $a^n$, then $p$ divides $a$.

If $a^n \in m\mathbb Z$, then all prime factors of $m$ divide $a^n$ and so divide $a$. Therefore, $a$ is multiple of $r=rad(m)$, and so $\sqrt{m\mathbb Z} \subseteq r\mathbb Z$.
Conversely, $r^n \in m\mathbb Z$, for every $n$ at least equal to the largest exponent in the prime factorization of $m$. Therefore, $r \in \sqrt{m\mathbb Z}$ and so $r\mathbb Z \subseteq \sqrt{m\mathbb Z}$.
For the second question, note that $700a \in 180 \mathbb Z$ implies $700a=180b$ and so $35a=9b$. Since $9$ and $35$ are coprime, $9$ must divide $a$, that is, $a \in 9 \mathbb Z$. The reverse inclusion is easy.
Comment: I'll give it a go.
Comment: Thank you! Now I understand the "radical ideal algorithm". Can you also explain the fraction ideal, please?
Answer: We wish to show that $(m\mathbb{Z} : n\mathbb{Z}) = \frac{m}{(m,n)} \mathbb{Z}$.
Courtesy of Elegant Proof that $m | xn \implies \frac{m}{(m,n)} | x$, I can now give a much simpler proof.
Take $x \in (m\mathbb{Z} : n\mathbb{Z})$. Then, by definition, $xn\mathbb{Z} \subset m\mathbb{Z}$. In particular, this means that there exists $k \in \mathbb{Z}$ such that $xn  = mk$. Hence, $m | xn$.
Let $d = (m,n)$. By Bezout's identity, there exist $a,b \in \mathbb{Z}$ such that $am + bn = d$. Thus $amx + bnx = dx$. Since $m | xn$, $m | bnx$. Clearly $m | amx$. Thus, $m | amx + bnx$, i.e. $m | dx$. Thus, there exists $r \in \mathbb{Z}$ such that $mr = dx$. Thus, $x = \frac{m}{d} r$, which shows $x \in \frac{m}{d} \mathbb{Z}$. That is, $x \in \frac{m}{(m,n)} \mathbb{Z}$. Thus, we have shown $(m\mathbb{Z} : n\mathbb{Z}) \subset \frac{m}{(m,n)} \mathbb{Z}$.
For the other containment, take $x \in \frac{m}{(m,n)} \mathbb{Z}$. Then there exists $s \in \mathbb{Z}$ such that $x = \frac{m}{(m,n)} s$. By definition, $\frac{n}{(m,n)} \in \mathbb{Z}$. Thus $t =\frac{ns}{(m,n)} \in \mathbb{Z}$. We compute
$$
mt = m \frac{ns}{(m,n)} = n \frac{m}{(m,n)} s = nx = xn
$$
Thus, there exists $t \in \mathbb{Z}$ such that $mt = xn$. Hence, for any $j \in \mathbb{Z}$ there exists $k = jt \in \mathbb{Z}$ such that $mk = mjt = mtj = xnj$. That is, for any $j \in \mathbb{Z}$ there exists $k \in \mathbb{Z}$ such that $xnj = mk$. This is precisely the statement that $xn\mathbb{Z} \subset m\mathbb{Z}$, which itself is precisely the statement that $x \in (m\mathbb{Z} : n\mathbb{Z})$. Thus, we have shown $\frac{m}{(m,n)} \mathbb{Z} \subset (m\mathbb{Z} : n\mathbb{Z})$.
We conclude $(m\mathbb{Z} : n\mathbb{Z}) = \frac{m}{(m,n)} \mathbb{Z}$.
Comment: I think I found a simpler proof of the first containment, but it will have to wait.
Comment: Yes. They are equal as sets.
Comment: Also, in case it wasn't clear, I use $(m,n)$ to mean $\gcd(m,n)$.
Comment: I'm not used to number theory, so it took a long time but I managed following your proof. Just to be perfectly clear: This is an equality of sets, not an isomorphism, correct?


How do I use Data.Concurrent.mergeIO?

Question: I see two functions mergeio and nmergeio in Data.Concurrent, but I can't find any examples of how they work.
Has anyone worked with these before?  My hope is that I can use these to get a function like "parMapM".
Answer: import Control.Concurrent (mergeIO, nmergeIO)

main = do
  xs <- mergeIO (map (*2) [1..10])
                (map (+3) [100..110])
  print xs

  xs <- nmergeIO [ map (\x->x*x) [1..10]
                 , map (\x->x+x) [1..10]
                 ]
  print $ maximum xs

Output:
[2,4,103,6,104,8,105,10,106,12,107,14,108,16,109,18,110,20,111,112,113]
100
The internal order may differ depending on how quickly each thread pitches back results.
Writing parMapM is a little tricky, but the result is nice:
import Control.Applicative
import Control.Concurrent
import Control.Concurrent.STM
import Control.Exception
import Control.Monad
import Data.Word
import System.IO

import qualified Data.ByteString as BS

main :: IO ()
main = do
  xs <- parMapM (reverse . show) $ replicate 4 (readFromNet 5)
  print xs

We'll read from /dev/urandom as a standin:
readFromNet :: Int -> IO [Word8]
readFromNet n = do
  h <- openFile "/dev/urandom" ReadMode
  let go :: Int -> IO [Word8]
      go 0 = return []
      go remaining = do s <- BS.head <$> BS.hGet h 1
                        ss <- go (remaining-1)
                        return (s:ss)
  go n

Finally the gory bits:
parMapM :: (a -> b) -> [IO [a]] -> IO [b]
parMapM f as = do
  kids <- newMVar []
  answers <- atomically $ newTVar []
  forM_ as $ \ a ->
    do mvar <- newEmptyMVar
       curkids <- takeMVar kids
       putMVar kids (mvar:curkids)
       let ax = do xs <- a
                   atomically $ do sofar <- readTVar answers
                                   writeTVar answers (sofar ++ xs)
       forkIO (ax `finally` putMVar mvar ())
  waitForChildren kids
  atomically $ map f <$> readTVar answers
  where
    waitForChildren kids = do ks <- takeMVar kids
                              case ks of
                                [] -> return ()
                                m:ms -> do
                                  putMVar kids ms
                                  takeMVar m
                                  waitForChildren kids

It works by having the children write their answers to a TVar while the main thread waits for the children to signal their completion.
Unfortunately, the results are "chunky" because readFromNet is unaware of communication issues, so we get all values from a given thread at once. If you don't mind making them get their hands dirty, you could do so as in the following:
main :: IO ()
main = do
  let threads = 3
      nbytes  = 10
      total   = nbytes * threads
  byte <- newEmptyMVar
  let thr = forkIO $ readFromNetwork nbytes byte
      go 0 = return []
      go n = do b <- takeMVar byte
                bs <- go (n-1)
                return (b:bs)
  sequence_ $ replicate threads thr
  values <- map (reverse . show) <$> go total
  print values

Then the worker looks like
readFromNetwork :: Int -> MVar Word8 -> IO ()
readFromNetwork n var = do
  -- or something...
  h <- openFile "/dev/urandom" ReadMode
  let go 0 = return ()
      go remaining = do s <- BS.hGet h 1
                        putMVar var (BS.head s)
                        go (remaining-1)
  go n

Comment: Thanks!  So I guess it doesn't work with IO actions, e.g.

    mergeIO (map getFromNetwork [...])
Comment: @Bill Both mergeIO and nmergeIO take pure lists — [a] rather than IO [a] — so trying to use an action such as getFromNetwork won't typecheck.

How do I use Data.Concurrent.mergeIO?


Rails 3 only need to edit one field from a loop

Question: Order has_many :items and Accepts Nested Attributes for.
Want to loop through the items in the Order form, but only need the item.qty field to be editable.  Would like to display the other fields as normal <%= item.name %>, etc.
I know that I can use readonly and disable or even clean it up with css, but wondering if there is a better way.
order form looks like this.
<%= form_for [current_company, @order] do |f| %>
 ...
  <%= f.fields_for :items do |item| %>
    <%= render :partial => 'item', :locals => { :item => item } %>
  <% end %>
 ...
<% end %>

item partial looks like this.

  <%= item.text_field :name %>
  <%= item.text_field :short_description %>
  <%= item.text_field :price %>
  <%= item.text_field :qty %>
   <%= item.text_field :full_price %>

Answer: <%= item.object.name %>
<%= item.object.description %>

etc


How to pass Parcelable to two or more Activities or Fragments?

Question: I can pass Parcelable to one Fragment or Activities but I can't pass Parcelable to two or more Fragment or Activities.
I have a ListView in Fragment when i click list item, list item details will be send to GetFragment1, GetFragment1 I have button to show more details of list item, I want to get Parcelable from SendFragment in GetFragment2 and GetFragment3.
This is Test.java
import android.os.Parcel;
import android.os.Parcelable;

public class Test implements Parcelable {

    private int studentNumber;
    private String studentName;
    private String studentFamily;

    public int getStudentNumber() {
        return studentNumber;
    }

    public void setStudentNumber(int studentNumber) {
        this.studentNumber = studentNumber;
    }

    public String getStudentName() {
        return studentName;
    }

    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }

    public String getStudentFamily() {
        return studentFamily;
    }

    public void setStudentFamily(String studentFamily) {
        this.studentFamily = studentFamily;
    }

    public Test() {
    }

    public Test(Parcel read) {
        studentNumber = read.readInt();
        studentName = read.readString();
        studentFamily = read.readString();
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel write, int flags) {
        write.writeInt(studentNumber);
        write.writeString(studentName);
        write.writeString(studentFamily);
    }

    public static final Parcelable.Creator<Test> CREATOR =
            new Parcelable.Creator<Test>() {
                @Override
                public Test createFromParcel(Parcel source) {
                    return new TestP(source);
                }
                @Override
                public Test[] newArray(int size) {
                    return new TestP[size];
                }
            };
}

In FragmentSend.java I want to send data to FragmentGet1.java and FragmentGet2.java and FragmentGet3.java, this is the code:
public class FragmentSend extends ListFragment {

    //    Classes
    TestReadData readData;
    TestDataSource dataSource;

    private List<Test> listTest;

    public FragmentSend() {
        // Required empty public constructor
    }

    @TargetApi(Build.VERSION_CODES.M)
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View layout = inflater.inflate(R.layout.fragment_send, container, false);

        readData = new TestReadData(getContext());
        dataSource = new TestDataSource(getContext());

       refreshStudentList(inflater);

    return layout;
}

public void refreshStudentList(LayoutInflater inflater) {

    listTest = readData.getAllStudentRows();
    ArrayAdapter<Test> testAdapter = new TestFragmentListAdapter(inflater.getContext(), listTest);
    setListAdapter(testAdapter);

}

    @Override
    public void onResume() {
        super.onResume();
        dataSource.open();
    }

    @Override
    public void onPause() {
        super.onPause();
        dataSource.close();
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);

        Test model = listTest.get(position);

         Bundle bundle = new Bundle();
         bundle.putParcelable("Student", model);

        FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

    Fragment fragmentGet1 = new FragmentGet1();
    Fragment fragmentGet2 = new FragmentGet2();
    Fragment fragmentGet2 = new FragmentGet3();

    fragmentGet1.setArguments(bundle);
    fragmentGet2.setArguments(bundle);
    fragmentGet3.setArguments(bundle);

    fragmentTransaction.replace(R.id.frame_container, fragmentGet1);
    fragmentTransaction.addToBackStack(null);
    fragmentTransaction.commit();

    }

in GetFragment1.java I can get Parclable successfully but in two other Fragments (GetFragment2.java and GetFragment3.java) the bundle will be null!
This is GetFragment1.java code for getting Parcelable:
I use this code for other two Fragments.
Bundle bundle;
bundle = this.getArguments();
    if (bundle != null) {
                model = bundle.getParcelable("Student");
                if (model != null) {

                    Log.i(LOG_TAG, String.valueOf(String.valueOf(model.getStudentNumber());

                }
            } else {
                Log.i(LOG_TAG, "LogDetailsFragment 'bundle' is null!");
            }

how can i send Parcelable for more Fragments?
Comment: Are you actually adding the other two fragments into the transaction, with .replace(), .add() or some other method?
Comment: @Kelevandos no, should I do this?
Comment: Well, yes, only then will the fragment get created and be able to receive its arguments :-) You do this for Fragment1 and that is why it does receive the Bundle just fine
Comment: @Kelevandos but I don't want to show GetFragment2 or GerFragment3, I just want to show GetFragment1 and pass Parcelable to all of theme, is there any way to do that?
Comment: So what do you need them for? Maybe some other class would do better? Please elaborate a bit on what you want to achieve :-)
Comment: @Kelevandos question Edited.
Comment: But why do you want to pass it to other fragments if you do not want to show these fragments at all?
Comment: @Kelevandos I just want to get studentNumber and show all details of this student, in GetFragment1 student details is Name And Family but In GetFragment2 and 3 student details is everything.
Comment: And do I understand correctly that the Fragments will be chained? The FragmentSend will open only FragmentGet1, FragmentGet1 will open FragmentGet2 and FragmentGet2 will open FragmentGet3?
Comment: @Kelevandos yes, that's right :D
Answer: Ok, your problem is in the sequence of things. In this part of your code:
Fragment fragmentGet1 = new FragmentGet1();
Fragment fragmentGet2 = new FragmentGet2();
Fragment fragmentGet2 = new FragmentGet3();

fragmentGet1.setArguments(bundle);
fragmentGet2.setArguments(bundle);
fragmentGet3.setArguments(bundle);

You are creating instances of all the 3 fragments, but then only using the instance of FragmentGet1. The other ones are not used. Later, when you create another instance of any of those Fragments, it will not have the args because it is a totally separate object.
That you need is to pass the bundle forward each time you create a new Fragment. If you want to create it from within an already-created fragment, it will look somewhat like this:
public void showNextFragment() {

    FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

    Fragment fragmentGet2 = new FragmentGet2();

    if(this.getArguments() != null)
        fragmentGet2.setArguments(this.getArguments());

    fragmentTransaction.replace(R.id.frame_container, fragmentGet2);
    fragmentTransaction.addToBackStack(null);
    fragmentTransaction.commit();

}

Put it into your FragmentGet1 and let me know if this if what you need :-)
EDIT:
To pass the Student object to an Activity, just do something like this:
    Student s = //get it here
    Bundle b = new Bundle();
    b.putParcelable("student", s);

    Intent i = new Intent(getActivity(), ThatOtherActivity.class);
    i.putExtra("extraWithStudent", b);
    startActivity(i);

And then to read the data in the Activity:
    Intent incomingIntent = getIntent();
    Bundle b = incomingIntent.getBundleExtra("extraWithStudent");
    Student s = (Student) b.getParcelable("student");

Comment: FragmentGet1 open an TabsActivity with two tabs: FragmentGet2 and FragmentGet3, should I pass bundle to TabsActivity first then pass it to two fragments?
Comment: Yeah, just pass it to the activity and then to the Fragments when you create the instances you will add().
Comment: can u tell me how to send Parcelable from fragment to activity?
Comment: Put it inside the intent you are using to start the activity, using the .putExtra(String, Bundle) method :-) Then, in Activity, use getIntent().getExtra(String) to read it.
Comment: I get this error:
'android.os.Bundle cannot be cast to com.saly.student'
would u please write the currect code. @KKelevandos


Search for filenames

Question: So I am trying to code an "A.I." through batch. The user will be able to enter in information, and the program will track keywords, and compile all data onto one text file in a specific folder. I have almost everything but a line that searches for all the filenames with a certain keyword. Here is an example. User: "Tell me EVERYTHING you know about GEORGE WASHINGTON" Program: Searches through memory for folder "George Washington" then gathers all the .txt files from that folder. It then types everything from those files to the user. Pls help, thanks :-)
Comment: @RB -  For some reason, the most common first projects of people new to batch (especially those between the ages of 15 and 19) are a chatbot or an RPG. No idea why.
Comment: Why are you doing this in batch? That's...not a suitable language! Your better option would be a language like Prolog which is designed for this sort of thing.
Answer: you can do:
@echo off
set "foldertosearch=George Washington"
cd C:\
for /d /r %%a in ("%fodertosearch%") do (
echo found folder: %%a
cd %%a
)
for /f %%b in (*.txt) do (
echo found file: %%b
type "%%b"
)
pause

i recommend you to change the C:\ of the 3rd line to a specific folder because i am not shure the for /d loop can handle a whole drive. use the where command instead.

Search for filenames


Neural network cost function oscillating with number of epochs

Question: I'm implementing a 4-5-3 neural network for the iris dataset with sigmoid activation and a cross entropy loss function. But the graph of the loss vs the number of epochs is oscillating and I have no idea why. Any help will be appreciated!
https://i.stack.imgur.com/zguAw.jpg
Comment: Your learning rate is too high.
Comment: Do you train by batch or the whole epoch at the time? Is your data sequentially put into training data or sampled randomly?
Comment: The whole epoch and I picked random examples from my training set, 120 random examples to be exact
Comment: my learning rate is 10^-5, and going lower didn't help.
Answer: Did you normalize the data? I got an oscillating loss curve on another problem and that helped.


Redis client times out when connecting

Question: I have a Redis cluster running on ElastiCache.
Multiple processes connect to the Redis cluster. Each process lives within a Docker container. The processes are not all the same -- I have a web process, a worker process, etc.
After a few days of operating normally, some of my web processes begin to time out when connecting to Redis. When I ssh into an affected web container and try to reach the cluster via redis-cli, my connection to the cluster times out. This tells me that the issue affects the entire container, and not just the web process.
When I use redis-cli from any other container, I connect without problems.
My web processes create new connections as needed, and close old connections when they're idle for a long time. My guess is that any given Docker container can open a certain number of connections before reaching some kind of limit. After a few days, my web containers reach that limit.
Any idea how to go about fixing this?
--
One more detail: for some reason, resetting my Redis cluster fixes the issue across all web containers. Maybe the Redis server imposes a limit on how many connections can be opened from a given IP address?
Answer: Josiah and I had a long discussion on the Redis Google group which helped solve my issue; hopefully the discussion can help someone else in the future.

Redis client times out when connecting


Is there a more elegant way to add usercontrols to a list?

Question: I have 10 custom usercontrol's with ID's usercontrol1, usercontrol2, usercontrol3......usercontrol10.
I want to add all these usercontrols to a List "allusercontrol". I do this with brute force like this
allusercontrol.Add(usercontrol1);
allusercontrol.Add(usercontrol2);
allusercontrol.Add(usercontrol3);
.
.
.
.
.

Is there a more elegant and easy way of doing this trivial task? You do see that the usercontrols ID's are a part of a series "usercontrol"+an int
Comment: Don't name your controls in such an anonymous way. What is more prone to errors: `Button1,Button2,Button2` or `BtnInsert,BtnUpdate,BtnDelet`?
Comment: @TimSchmelter Updated my question for user control
Comment: Where are these usercontrols coming from? Are they already on an aspx page?
Comment: Yes they are already in the aspx page.
Answer: I would advise against this approach since it's prone to errors. What if you want to rename them, what if you'll forget about this and add other controls with name ButtonX that should not be in this list?
Instead i would collect them in a container control like Panel.
Then you can use LINQ to find the relevant Buttons:
var myButtons = myPanel.Controls.OfType<Button>();

Enumerable.OfType will filter and cast the controls accordingly. If you want to filter them more, you could use Enumerable.Where, for example:
var myButtons = myPanel.Controls
                       .OfType<Button>()
                       .Where(btn => btn.ID.ToLower().StartsWith("button"));

Now you can iterate those Buttons, for example:
foreach(Button btn in myButtons)
{
    // do something amazing
}

Or you can just call ToList() to get a List<Button> (the core of your question):
List<Button> allbuttons = myButtons.ToList();

Comment: Thanks Tim, that's a nice solution.
Answer: try with this code
List<UserControl> controls = new List<UserControl>
{
    usercontrol1,
    usercontrol2,
    usercontrol3
};

Comment: There would still be a lot of code, consider a scenario of 100 usercontrols.
Comment: Ok, Try with this code YourContainer.Controls.OfType();
Answer: Use Control.ControlCollection.AddRange - look here


Submit handler in hook_form_alter not working in d8

Question: I have hook_form_alter as follows :
function auto_ga_form_alter(&$form, &$form_state, $form_id) {
    global $base_url;
    if($form_id == 'node_p_request_form' || $form_id == 'node_p_request_edit_form' || $form_id == 'node_f_pro_request_form' ) {
      $form['#submit'][] = 'custom_form_submit_fn';
      $form['actions']['submit']['#submit'][] = 'custom_form_submit_fn';
   }
}

function custom_form_submit_fn(&$form, $form_state) {
  echo 'reached in submit handler';exit;
}

But its not going to the submit handler . both usage ( $form['#submit'][] OR  $form['actions']['submit']['#submit'][]) of submit handlers not working
And idea ??
Comment: Have you checked this Url "https://www.drupal.org/node/2637958" ? Hope this will help you.
Comment: @PallaviSugandhi No luck , its not working even i tried with **mymodule_form_node_form_alter** , its going to the form_alter , but not to the submit handler , I think its the issue with button i specified , not sure though . Is there any way to find which button is clicked
Answer: What you are doing looks like it should work.
Doing an echo is undetecable in the submit handler, since Drupal will do a redirect after the POST request and thus clearing all of the output generated but Drupal in the actual submit handler.
A simple way to test if the submit handler is called or not is to insert a die()
Reasons for submit handler not being called could be:

You submit the form with a button you haven't added a submit handler on and that already have one or more attached to it.
Another alter hook removes your submit handler (unlikely)
Answer: In Drupal 8 the parameters are changed
Please add following parameters in hook_form_alter and example_form_submit_handler:
hook_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id)

example_form_submit_handler($form, \Drupal\Core\Form\FormStateInterface $form_state)

Hope this will help you.
Comment: It's doesn't change anything to specify the FormStateInterface in function signature


Prove Euler's formula

Question: If $F(x,y,z) \in \mathbb{C}[x,y,z]$ is a homogeneous polynomial of degree $n$, prove the Euler's formula.
$$XF_X+YF_Y+ZF_Z=nF$$
Could you give me a hint how we could show this?
EDIT: Could we show it like that?
Let $F(x,y,z)=\sum_{i+j+k=n} a_{ijk} \ x^i \ y^j \ z^k$
$$F_x(x,y,z)=\sum_{i+j+k=n} a_{ijk} i x^{i-1} y^j z^k$$
$$xF_x(x,y,z)=x\sum_{i+j+k=n} a_{ijk} i x^{i-1} y^j z^k=\sum_{i+j+k=n} a_{ijk} i x^{i} y^j z^k$$
$$yF_x(x,y,z)=y\sum_{i+j+k=n} a_{ijk} x^{i}j y^{j-1} z^k=\sum_{i+j+k=n} a_{ijk}  x^{i} j y^j z^k$$
$$zF_x(x,y,z)=z\sum_{i+j+k=n} a_{ijk} x^{i} y^{j} k z^{k-1}=\sum_{i+j+k=n} a_{ijk}  x^{i}  y^j k z^k$$
$$xF_x+yF_y+zF_z=(i+j+k) \sum_{i+j+k=n} a_{ij} x^i y^j z^k=nF$$
Comment: Does $F_{X} (F_{Y}, F_{Z}$ respectively) denote the formal derivative with respect to $X$?
Comment: Yes, that's what is meant..
Answer: Hint: prove that it is true for a monomial $X^iY^jZ^k$ of degree $n=i+j+k$, and that both sides are linear in $F$.
Comment: Since taking de derivative is linear and multiplication is distributive.
Comment: @evinda Yes, that is correct!
Comment: BrunoJoyal Why does it stand that if it is true for a monomial $X^iY^jZ^k$, it is also true for any polynomial $F(X,Y,Z)$ ?
Comment: I edited my post... Could you tell me if it is right?
Comment: @BrunoJoyal But why do we take such a polynomial? Why doesn't it have for example a constant term?
Comment: @evinda Homogeneous polynomials are to projective space what polynomials are to affine space.
Comment: @BrunoJoyal Could you explain it further to me?

Prove Euler's formula


png.h file not found - Linux

Question: I am trying to run this in linux ubuntu. When I type make it says
rgb_image.cc:26:24: fatal error: libpng/png.h: No such file or directory
 #include <libpng/png.h>

Then i followed this to install png.h.
sudo install libpng-dev

But now its telling me
install: missing destination file operand after 'libpng-dev'

What do I do?
Please help, thanks.
Answer: try  rather this:
sudo apt-get install libpng-dev

Then maybe go askubuntu.com ;)
Answer: For centOS 7 you can try
yum -y install libpng*

Answer: With Ubuntu 18, /usr/include/png.h moved to /usr/include/libpng/png.h
A workaround is this:
ln -s /usr/include/libpng/png.h /usr/include/png.h
Or you can configure your build to use include directory /usr/include/libpng
Answer: For Centos 8, I got the below warning message :

Warning: Header file <png.h> not found.
This host has no libpng library.
Disabling support for PNG framebuffers.

and I solved it using the command :

sudo yum install libpng-devel
Answer: For Centos 7 use below

libpng-devel : Development tools for programs to manipulate PNG image format files
yum install libpng-devel

Comment: What is the difference compared to the above?

png.h file not found - Linux


Does intellij CE support .jsp?

Question: I'm following a tutorial in the net and i cant seem to produce the supposed output, and whenever i go to my .jsp file, there's a pop up on the top area saying "try IntelliJ IDEA Ultimate".
Answer: IntelliJ IDEA Community edition doesn't support JSPs and app servers.
You can find more details in the editions comparison matrix.
Comment: @dfrankow Yes, JSP navigation and refactorings are supported. You can get a trial version and use it for 30 days to see yourself what's supported.
Comment: I don't see "JSP" in that matrix, but maybe it's in "Java EE"? Any idea or links to what the JSP support looks like? Does it allow you to control-click navigate, or refactor?

Does intellij CE support .jsp?


Poisson model without exponential relationship between Y and X

Question: Im having a hard time understanding how to fit a count model for data that i dont think is exponentially related.
$$E[Y|X] = e^{\beta_0 + \beta_1x}$$
Is the typical relationship when it comes to poisson regression. However what if i dont think the independent variable and dependent variable are related through a exponential relationship? What if its linear? Should i still use a poisson / negative binomial regression?
Comment: "What if it is linear?" Over what range of values? Consider the problem that arises if the probability is proportional to the value.
Comment: I used linear as an example but it could be any other relationship. If i wanted to not assume a exponential relationship how can i adjust say to linear, log, ect. If i apply the transformations on the variables themselves they are transformed in the exponential context.
Answer: Just use the "identity" link. Here is some R code to show that it works.
set.seed(12345)
n = 1000000
beta0 = .40
beta1 = .75
x = rnorm(n, 10,1)
y = rpois(n,beta0+ beta1*x)
fit = glm(y ~x, family = poisson(link = "identity"))
summary(fit)

The estimation recovers the true $\beta$'s nicely:
Coefficients:
            Estimate Std. Error z value Pr(>|z|)
(Intercept) 0.400517   0.027685   14.47   <2e-16 ***
x           0.749994   0.002781  269.67   <2e-16 ***

Here, my simulation was set so that negative means for the Poisson distributions are nearly impossible.  That is one thing you have to worry about with identity link though - you might wind up predicting a negative mean with you model. With the default log link (which implies an exponential function as you note), this can't happen.
Comment: This is really helpful thanks!


Determining the type of motherboard in a server

Question: I was wondering if I could get some advice from the community. I am trying to identify a type of motherboard used in this particular product:
LINK TO PRODUCT
Does anyone know what type of motherboard it is, ITX, Micro ATX etc?
Thank you
Comment: This seems off topic to me
Answer: Just looking at it, it appears to be mini-ITX, but as often as not these types of things are proprietary.  As well, if you're planning to replace it, you'd have to modify the case because it doesn't have a swappable faceplate.  They don't state it in the specs because they don't intend for it to be replaceable (except as a repair part).


Slow mongodb FindOneAndUpdate

Question: I'm having trouble with the following findOneAndUpdate MongoDB query:
<code>planSummary: IXSCAN { id: 1 } keysExamined:1 docsExamined:1 nMatched:1 nModified:1 keysInserted:1 keysDeleted:1 numYields:0 reslen:3044791

locks:{ Global: { acquireCount: { r: 1, w: 1 } }, Database: { acquireCount: { w: 1 } }, Collection: { acquireCount: { w: 1 } } }

storage:{} protocol:op_query 135ms

writeConcern: { w: 0, j: false }
</code>
As you can see it has execution time of +100 ms. The query part uses an index and takes less than 1ms (using 'Explain query'). So it's the write part that is slow.
The Mongo instance is the master of a 3 member replica set. Write concern is set to 0 and journaling is disabled.
What could be the cause of the slow write? Could it be the update of indices?
MongoDB version 4.0
Driver: Node.js native mongodb version 3.2
Edit: I think it might be the length of the result. After querying a document smaller in size, the execution time is halved.
Answer: <code> reslen:3044791
</code>
This was the source of the bad performance. Reducing this by adding a projection option to only return a specific field improved the execution from ~90ms on average to ~7ms.

Slow mongodb FindOneAndUpdate


Formatar número no reportviewer?

Question: Estou tentando formatar um numero no ReportViewer e não estou conseguindo, pra isso estou tentando usar a função Format do TextBox no ReportViewer. O número é um código e estou tentando preencher com 3 zeros à esquerda. Estou tentando assim: =FormatNumber(Fields!terminal.Value.codigo, String.Format("{N:000}")), mas não está funcionando. Como fazer isso?
Answer: O correto seria:
Format(Fields!terminal.Value.codigo, "0000");

Referencias:

Adding Style and Formatting to a ReportViewer Report
Utilizando expressões no Report Viewer

Formatar número no reportviewer?


Is there any relationship among cosine similarity, pearson correlation, and z-score?

Question: I'm wondering if there is any relationship among these 3 measures. I can't seem to make a connection among them by referring to the definitions (possibly because I am new to these definitions and am having a bit of a rough time grasping them).
I know the range of the cosine similarity can be from 0 - 1, and that the pearson correlation can range from -1 to 1, and I'm not sure on the range of the z-score.
I don't know, however, how a certain value of cosine similarity could tell you anything about the pearson correlation or the z-score, and vice versa?
Comment: z score of *what*? z scores of *some* things might be related to Pearson correlation, Z scores of other things may not. For example, if you internally standardize your original variables then the Pearson correlation between x and y is the expected product of their z-scores. Or you might be talking about z-scores *of* Pearson correlations (Pearson correlations minus their expectation under some condition all divided by the standard error of the Pearson correlation), which would certainly be related to the Pearson correlation.
Comment: Direct relation: https://stats.stackexchange.com/a/22520/3277
Answer: The cosine similarity between two vectors $a$ and $b$ is just the angle between them
$$\cos\theta = \frac{a\cdot b}{\lVert{a}\rVert \, \lVert{b}\rVert}$$
In many applications that use cosine similarity, the vectors are non-negative (e.g. a term frequency vector for a document), and in this case the cosine similarity will also be non-negative.
For a vector $x$ the "$z$-score" vector would typically be defined as
$$z=\frac{x-\bar{x}}{s_x}$$
where $\bar{x}=\frac{1}{n}\sum_ix_i$ and $s_x^2=\overline{(x-\bar{x})^2}$ are the mean and variance of $x$. So $z$ has mean 0 and standard deviation 1, i.e. $z_x$ is the standardized version of $x$.
For two vectors $x$ and $y$, their correlation coefficient would be
$$\rho_{x,y}=\overline{(z_xz_y)}$$
Now if the vector $a$ has zero mean, then its variance will be $s_a^2=\frac{1}{n}\lVert{a}\rVert^2$, so its unit vector and z-score will be related by
$$\hat{a}=\frac{a}{\lVert{a}\rVert}=\frac{z_a}{\sqrt n}$$
So if the vectors $a$ and $b$ are centered (i.e. have zero means), then their  cosine similarity will be the same as their correlation coefficient.
TL;DR Cosine similarity is a dot product of unit vectors. Pearson correlation is cosine similarity between centered vectors. The "Z-score transform" of a vector is the centered vector scaled to a norm of $\sqrt n$.
Comment: +1. latexnazi comment: `\|` often looks better than `||`, and `\lVert ... \rVert` is the best way to write it.
Answer: To convert a z-score to a cosine, use the cumulative distribution function for a Gaussian distribution. Find the value of the Gaussian cdf corresponding to the z-score value. Subtract 0.5 from that value, multiply by 2, and assume that value is the sine of an angle. Use the arcsine function to find that angle. Then take the cosine of that angle. Voila!


Jogo de Chute em Python. Alguém tem alguma dica que como reduzir ou melhorar esse código sem usar funções?

Question: from random import randint
from time import sleep

valor = randint(1, 20)
tentativa = 0
chute = 0
print()
while chute != valor:
    chute = int(input('\nChute um número: '))
    tentativa += 1

    while chute < 1 or chute > 20:
        chute = int(input('Chute um valor entre 1 e 20.'))
        break

    if chute < valor:
        print('Você jogou baixo demais!')
        resp = input('Deseja continuar: S/N ').upper()
        while resp not in 'SN':
            resp = input('Digite S ou N ').upper()
        if resp == 'N':
            break

    elif chute > valor:
        print('Você jogou alto mais!')
        resp = input('Deseja continuar: S/N ').upper()
        while resp not in 'SN':
            resp = input('Digite S ou N ').upper()
        if resp == 'N':
            break

    else:
        print(f'\nAcertou!')
print('\nFinalizando...')
sleep(1)
print(f'\nAo todos foram feitas {tentativa} tentativas.')

Answer: Consegui fazer essa solução:
from random import randint

computador = randint(0, 10)
tent = 0

jogador = int(input('Tente adivinhar o número que o computador escolheu (entre 0 a 10): '))
tent += 1
while computador != jogador:
    if computador > jogador:
        jogador = int(input('Mais... Tente novamente: '))
        tent += 1
    else:
        jogador = int(input('Menos... Tente novamente: '))
        tent += 1
print(f'Parabéns! Você acertou! Precisou de {tent} tentativas.')

Comment: O `tent = 0` e o `tent += 1` antes do `while` são desnecessários  apenas inicie `tent = 1`.


sequelize.sync({ force: true }) is not working some times

Question: i am using gulp tasks for migration of database. For testing purpose i am using different database. so i need exactly same database. i am trying to do with sequelize.sync({ force: true }) but its not working.
i am having my all models in portal-model. here is the code:
const models = require('portal-models');
gulp.task('migrate', ['create-database'], (done) => {
  models.sequelize.query('SET FOREIGN_KEY_CHECKS = 0')
  .then(() => models.sequelize.sync({ force: true, alter: true }))
....
....
....
)

With Force: true it should work but for me i am getting error like mydatbaseName.tablename is not exists.
i have created new test database. i dont want to manually create everything in testdatabase, so i am using migrations but i gusse sync is not working properly.
Can anyone tell, exactly what should i follow?
Thanks in Advance.
Comment: @Shivam: No , i am not using sequelize-cli. i am using  "sequelize": "^3.24.3".
Comment: Are you using sequelize-cli for migrations
Comment: If manually i have created tables, then it is working for insert queries. but i dont want to create tables manually. Force: true should map schema.
Comment: i have added models.sequelize.sync({ force: true, logging: console.log })), in console now i can see all the tables are droped and then again created. but still while insertion i am getting error  ER_NO_SUCH_TABLE: Table 'DatabaseName.TableName' doesn't exist.
Answer: Finally i found the mistake.
models.sequelize.sync({ force: true })
 it was working properly but i was not able to see any logs on command prompt so i thought sync is not working properly. I have added
models.sequelize.sync({ force: true, logging: console.log }))
 With this i was able to see the log, it was dropping all tables and again creating. The problem was not with sequelize.sync() . Problem was with my database name, it was referring development database only, and i was executing queries on testDatabase.
before running test, i just changed my database like
export MYSQL_DATABASENAME = test_database_name .
 And issue solved.


list all files in directory under different user python

Question: I need to list absolute paths to files in a directory for python 3.7.5. Now the issue is that neither of the solutions specified here work:
Get absolute paths of all files in a directory
Perhaps because I log in to a different user and my home directory changes: sudo su - my_user_name
Such solutions:
files = [Path(x).absolute() for x in os.listdir(source_folder)]

or
files = [os.path.abspath(x) for x in os.listdir(source_folder)]

Result in appending current working dir to the correctly found names of the files. So, if I list directory: /other_home/data/gene_data (which has a file named my_file.tsv), but I am in some /new_home/def/cram/my_project_name, The above solutions produce the path: /new_home/def/cram/my_project_name/my_file.tsv and not /other_home/data/gene_data/my_file.tsv. Is there a way still to achieve that?
Answer: os.listdir returns the filename without path, which makes it a relative path based on source_folder. os.path.abspath doesn't know about source_folder. All it knows about is the current working directory. So, it assumes CWD is the relative path that you want to be made absolute.
You could join the known path component before making it absolute
files = [os.path.abspath(os.path.join(source_folder, x))
            for x in os.listdir(source_folder)]

When using Path you have a similar problem. You created the path from the filename which lacks its path component, so Path assumes you meant the current working directory. Instead have Path do the directory enumeration for you so that it passes back properly qualified Path objects.
files = [x.absolute() for x in Path(source_folder).glob("*")]


PDO query fails to execute when AUTO_INCREMENT included in creation script, but query seems to be valid

Question: I'm trying to get some test scripts set up with PHPUnit using in-memory databases, but I'm having trouble creating the databases correctly. When I first ran the queries it was running fine, but I'd forgotten to add AUTO_INCREMENT to the id field. Once I added that, PDO would drop out with a fatal error any time the script ran. I've tried running the same query through phpMyAdmin to see if it works (it goes through without any complaints) and even used that to perform the action I wanted and copied the SQL it ran without any luck, so I'm kind of at a loss for what's going on. If anyone can give me a hand with this it'd be a big help. Query can be found below
CREATE TABLE IF NOT EXISTS `checks` (
    `id` int(60) NOT NULL AUTO_INCREMENT,
    `check_type` varchar(255),
    `purchase_id` varchar(255),
    `price` varchar(255),
    `time` varchar(255),
    `user_id` varchar(255),
    `email` varchar(255),
    `site_id` varchar(255),
    PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

VARCHAR's used for everything except ID because those are running through an automated script and the data type can vary. It's a MySQL database if that makes a difference. Thanks for any help you can give
edit: Adding the full error message as requested:

SQLSTATE[HY000]: General error: 1 near "AUTO_INCREMENT": syntax error
Comment: I tested that CREATE TABLE through PDO against MySQL 5.5.30.  It works fine.  You should edit your question and include the full error message, if any.
Comment: I don't get that error in my test, either running the query ad hoc in  the mysql client, or when running via PDO.  Have you tried removing the AUTO_INCREMENT=1 table option in the last line, since that's redundant anyway?  I.e. a new CREATE TABLE sets the auto increment to 1 by default.
Comment: What version of MySQL are you using?  I can try testing on the same version.  Find out:  `SELECT VERSION()` or `SHOW VARIABLES LIKE 'version'`.
Comment: Two points.1/  In-memory databases should  you not be using SQLite?2/  Should you be creating tables in PHPUnit?
Comment: Will do, although it's just a generic syntax error message
Comment: Bingo, we have a winner. I forgot that the test database stored in memory was using sqlite rather than mysql like the real database used by the system. Thanks David
Answer: I was getting the same thing when I switched to using PDO.  Remove the NOT NULL on the id field.  I don't know why... don't see any documentation.
CREATE TABLE IF NOT EXISTS `checks` (
    `id` int(60) AUTO_INCREMENT,
    `check_type` varchar(255),
    `purchase_id` varchar(255),
    `price` varchar(255),
    `time` varchar(255),
    `user_id` varchar(255),
    `email` varchar(255),
    `site_id` varchar(255),
    PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;


Open sets having open images in $R^2$

Question: Let $h:\Bbb R^2\to\Bbb R^2$ be a surjective function such that $\|h (x)-h (y)\|\ge 3 \|x-y\|$.
Prove that the image of every open set in $\Bbb R^2$ under the map $h$ is open in $\Bbb R^2$.
My question is that as the limit of the given function remains greater equals 3 so can it be proved continuous and
Then as not every continuous functions show that image is open then??
Comment: hint: show that $h^{-1}$ is well defined and continuous. The latter statement then implies the claim by defintion.
Comment: How does continuity imply open sets??
Comment: Continuity of the inverse map.
Answer: if $h(x)= h(y)$ for some $x, y$ whe have, by assumption, $$0=||h(x)-h(y)||\ge 3 ||x-y|| \ge 0$$
which implies $x=y$, in other words $h$ is one-to-one, so $g:=h^{-1}$ is well defined. $g$ is continuous (even Lipschitz) since (note that $h$ is assumed to be onto) given $v,w $ we have unique $x,y$ such that $h(x) = v, h(y) = w$ so $g(v) = x, g(w) = y$, and
\begin{eqnarray}
||v-w|| &=& ||h(x) - h(y)|| \\
& \ge & 3 ||x-y||  \\ &=& 3 ||g(v)-g(w)||
\end{eqnarray}
If now $U $ is an open set then $h(U) = g^{-1}(U)$ is open since $g$ is continuous.
Comment: thanks for clarifying the bound

Open sets having open images in $R^2$


What does "by finitary methods" actually mean, in regards to Hilbert's proof of consistency program?

Question: David Hilbert wanted to establish the consistency of mathematics, and in particular Peano Arithmetic, using finitary methods. This program is widely thought to have completely failed, due to Kurt Godel's incompleteness theorems. However, as far as I know, Hilbert never gave a formal definition of "finitary methods". Has any mathematician ever gave a rigorous definition of "finitary methods"? I wonder if this has ever been formalized in the mathematical literature.
Comment: If I recall correctly, "finitary methods" refers to the purely constructive principles by which an affirmative answer to the problem would need to follow in order to be considered satisfactory. In other words, any proof is not allowed to use the notion of the complete set of natural numbers
Answer: There is now a large and interesting literature on this topic on the extent of finitistic methods, too much to review here.
One headline: William Tate, for one, has argued in detail that Hilbert's finitary methods are (or rather, should have been) what are capturable in the formal theory of Primitive Recursive Arithmetic.
But this isn't universally agreed. For example, Charles Parsons has argued that finitistic arithmetic doesn't reach as far.
For much more on this and related debates, you could usefully see for a start the article on Hilbert's Program in the Stanford Encyclopaedia, and some of the references there.


What does the Steak N' Shake Time Machine commercial's "smart stuff" mean?

Question: I would like to know if there is any physical/mathematical significance to the following expression:
$$m\left(\left.\gamma v^{2}\right|_{t_{0}}^{t_{1}}-c^{2}\int_{v_{0}}^{v_{1}}{\frac{2v/c^{2}}{2\sqrt{1-v^{2}/c^{2}}}\:dv}\right)$$
For reference, starting at 21 seconds
Does this equation have any real meaning and if so, what does it mean? I do notice an integral.
Answer: It is junk, the units don't make sense. But the integrand is the velocity over c of a body accelerating towards lightspeed. The gamma is probably the Lorentz factor.
Comment: Well, of course the units don't match. They intentionally omitted some factors, or people would copy their time machine! :-)
Answer: the integrand looks like the Lorentz factor from special relativity. lots of things cancel and the whole thing, in its entirety, just looks like junk to be honest.
From reading comments on other posts I think that people here might not view this question favourably, since you've not typed the maths up yourself (so people have to go looking) and many wouldn't expect stuff thrown in on a fast food advert to have any significant mathematical meaning.


Multinomial Distribution for Naive Bayes

Question: I'm mainly confused because of some of the wording in this CV post. Multinomial Naive Bayes.
Mainly, this line:

In summary, Naive Bayes classifier is a general term which refers to conditional independence of each of the features in the model, while Multinomial Naive Bayes classifier is a specific instance of a Naive Bayes classifier which uses a multinomial distribution for each of the features." by jlund3.

Why is each feature $x_i$ a multinomial distribution, and not the product $\prod{P(x_i|c)}$ a multinomial distribution?
$$P(c|X) \propto \prod{P(x_i|c)} * P(c)$$
If the product of probabilities is distributed as a multinomial, that makes sense to me since
$$\prod{P(x_i|c)} \propto \prod{{p_i}^{x_i}} $$
I don't really understand how each feature itself could be distributed as a multinomial, however. Wouldn't each $x_i$ end up being a multinomial with two labels ($x_i$ == count of x_i.   $x_{not i}$ == count of every other word)
Any help would be much appreciated!
Answer: Take throwing a dice for example, the result $X$ can be a random number in $1,2,..,6$. When we do Bayesian parameter estimation, we can assume the probability of throwing a $1$ is $p_1$, throwing a $2$ is $p_2$,..., and so on. Hence, we want to estimate $(p_1,p_2,...,p_6)$. If we throw the dice $N$ times, we get $1$ for $c_1$ times, $2$ for $c_2$ times. We denote the result as a vector $\textbf{c}=(c_1,c_2,..,c_6)$, where $c_1+c_2+...+c_6=N$. Then the likelihood will be $\prod_{j=1}^6p_{j}^{c_j}$ ,which is exactly multinomial distribution. If $N=1$, only one dimension of $\textbf{c}$ will be 1, the rest will be 0. As you can see, this feature $X$ is a multinomial distribution.
Youtub videos Bayesian Naive Bayes provide detailed explanation of multinomial Naive Bayes which I found very useful.


How to save the state of an ImageButton

Question: I am trying save an ImageButton's path in savedInstanceState in order not lose image for rotating the phone. But only one time it's working after that the path value i equal null (path==null)
<code>@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentLayout(R.layout.contact_information_wga800);

    if (savedInstanceState != null) {
        String profilefirstname = savedInstanceState.getString("firstname");
        firstname.setText(profilefirstname);
        String profilepath=savedInstanceState.getString("path");
        if(profilepath !=null){
            imagebutton.setImageBitmap( BitmapFactory.decodeFile(profilepath));
        }
    }

@Override
public void onSaveInstanceState(Bundle savedInstanceState)
{
    savedInstanceState.putString("firstname", firstname.getText().toString());
    savedInstanceState.putString("path", media_path);
    super.onSaveInstanceState(savedInstanceState);
}
</code>
This is the part when I set in imagebutton bitmap using camera or android gallery.
<code>switch(requestCode) {
    case REQUEST_CAMERA:
        if (resultCode == RESULT_OK) {
            final Bundle extras = data.getExtras();
            bmp = (Bitmap)extras.get("data");
            if( bmp != null ) {
                final File f = this.getFileStreamPath("ping_media.jpg");
                if (f.exists()) {
                    f.delete();
                }
                try {
                    final FileOutputStream out = this.openFileOutput("ping_media.jpg",MODE_PRIVATE);
                    bmp.compress(CompressFormat.JPEG, 12, out);
                    out.close();
                    media_path = f.getAbsolutePath();
                    if(dm.densityDpi>=200) {
                        contactimg.setImageBitmap(getRoundedCornerBitmap(getResizedBitmap(bmp, 72, 72), 72));
                    } else if(dm.densityDpi>130 && dm.densityDpi<200) {
                        contactimg.setImageBitmap(getRoundedCornerBitmap(getResizedBitmap(bmp, 48, 48), 48));
                    } else {
                        contactimg.setImageBitmap(getRoundedCornerBitmap(getResizedBitmap(bmp, 32, 32), 32));
                    }
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        break ;
    case REQUEST_SELECT_PHOTO:
        if( resultCode != 0 ) {
            final Cursor c = managedQuery(data.getData(),null,null,null,null);
            if (c.moveToFirst()) {
                media_path = c.getString(1);
                bmp = BitmapFactory.decodeFile(media_path);
                contactimg.setImageBitmap(getRoundedCornerBitmap( getResizedBitmap(bmp, 48, 48), 48));
            }
        }
        break;
}
</code>
should I do here so anytime rotating the phone I didn't lose imagebutton's bitmap.
Answer: It seems like you are using the member variable media_path to store the path. You need to update this member when reading the path from the Bundle again in onCreate. Otherwise it is still null when you try to save it in onSaveInstanceState (except when your switch block has been run in the mean time).

How to save the state of an ImageButton


Como compartilhar um áudio do diretório interno raw?

Question: Tenho vários áudios armazenados no diretório raw do app e gostaria de compartilhar com outros aplicativos, como o whatsapp por exemplo, porém achei muito confusa a documentação sobre como configurar o File provider
AndroidManifest.xml
 <provider
        android:name="android.support.v4.content.FileProvider"
        android:grantUriPermissions="true"
        android:exported="false"
        android:authorities="com.namepackage.fileprovider">

        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/filepaths"/>

    </provider>

Ai vem a configuração do filepaths que tenho dúvida como resolver, está assim:
filepaths.xml
 <paths>
<files-path name="files" path="/" />

E o Intent em si:
  File imagePath = new File(context.getFilesDir(), "nomearquivo.mp3");
        Uri uri = FileProvider.getUriForFile(context,"com.namepackege.fileprovider",
                imagePath);
        Intent share = new Intent(Intent.ACTION_SEND);
        share.putExtra(Intent.EXTRA_STREAM, uri);
        share.setType("audio/mp3");
        share.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        share.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(share);

Mas esse código não funciona, gostaria como preciso alterá-lo afim de que funcione
Comment: Me parece que não é possível apenas usando o FileProvider, segundo o CommonsWare nessa [resposta](https://stackoverflow.com/questions/38742840/sharing-a-file-in-the-raw-folder-with-a-fileprovider), você tem duas alternativas: 1) Criar um FileProvider que faça acesso aos resources da pasta raw. 2) Usar o StreamProvider que implementa essa lógica: https://github.com/commonsguy/cwac-provider
Answer: Uma forma, além de outras, de fazer isso, é salvar o arquivo primeiro no dispositivo antes de enviar. Veja um método simples:
public Uri shareItemRaw(int songInRawId, String songOutFile) {
    File dest = Environment.getExternalStorageDirectory();
    InputStream in = getResources().openRawResource(songInRawId);

    try {
        OutputStream out = new FileOutputStream(new File(dest, songOutFile));
        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf, 0, buf.length)) != -1) {
            out.write(buf, 0, len);
        }
        in.close();
        out.close();
    } catch (Exception ignored) {
    }

    return Uri.parse(
        Environment.getExternalStorageDirectory().toString() + "/" + songOutFile);
}

Sendo assim, você criar seu intent desta forma:
Intent share = new Intent(Intent.ACTION_SEND);
share.putExtra(Intent.EXTRA_STREAM, shareItemRaw(R.raw.song, "song.mp3"));
share.setType("audio/*");
share.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
share.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(share);


Family vs. Child when a girl is chosen, what is the probability that the second child is a girl, textbook clarification?

Question: In a family with two children, what are the chances, if one of the children is a girl, that both children are girls?
I was able to understand the difference between selecting a child and a family, for the conditional probability question above. However, there is a follow-up paragraph about this question that I do not understand. In my textbook Fundamentals of Probability with Stochastic Processes, it says

Is the sentence "In fact, the probability that a family with two girls is selected equals
twice the probability that a family with one girl is selected." referring to when a child is selected, rather than when a family itself is selected? The entire paragraph was very confusing -- I did not understand the context that the author is explaining. How can P(girl, girl) = 1/2? In what context is the last sentence from?
Answer: Suppose there are four families with two children each. One family has a (boy,boy), one a (boy,girl), a (girl,boy) and a (girl,girl). Out of these 8 children, you pick one, which turns out to be a girl. There are four ways to pick a girl, and in half the cases that girl is from the (girl,girl) family.


Losing at Spider Solitaire

Question: Spider Solitaire has the property that sometimes none of the cards in the final deal can "go" and so you lose, regardless of how much progress you have made beforehand. You would have known that you would lose had you seen the final ten cards before the game started.
I wonder if we can calculate the probability of this happening.
To be clear, I want to find the probability that the final ten cards out of two packs of well-shuffled cards comprise cards no two of which are exactly one away from each other numerically (only the values matter, not the suits).
Note: there are several variants of Spider solitaire. I'm primarily interested in the standard 104-card, four-suit game.
Comment: @JonathanChristensen: An example of the situation I am describing is the following. Say that there is a nine of spades among the last ten cards to be dealt. Assume that there is also a jack among the ten last cards. Now if it happens that there is a single column with a ten of spades prior to dealing those last ten cards, and if it also happens that you have made enough progress so that you have some choice about which column that ten of spades will occupy. Then if you backtrack the last deal you may be able to arrange a column with ten-nine of spades, and you can move that column on the jack.
Comment: Not an answer, but a simulating it 10,000,000 times gives an estimate of 0.00585, so you expect it to happen about once in every 170 games.
Comment: @JyrkiLahtonen The question is specifically about the situation in which no matter how the rest of your cards are arranged it's impossible to do anything with the final ten, so taking back the top ten certainly won't help you.
Comment: I recall having rescued some games with a trick like the above. The idea can be extended to stacks with more cards. The ability to backtrack deals is the reason why my success rate in win7 is about 80% but in winXP it was (towards the end) something like 60%.
Comment: Note than in Win7 (unlike WinXP) version of the game you have the option to take back dealing the final ten cards. This gives you more options. If you have made enough progress prior to that point you may be able to arrange one of the newly dealt cards to extend an existing single suit sequence. Which may or may not help your cause.
Comment: Ah, I see. I don't actually play Spider Solitaire...
Answer: There can be $2$ to $7$ different card values, and $k$ card values can occur in $\binom{14-k}k$ different value combinations. The number of ways of choosing $10$ cards with exactly $k$ different card values can be found using inclusion–exclusion: There are $\binom{8k}{10}$ ways to choose $10$ cards with values in a given set of $k$ values, so there are
$$
\sum_{j=2}^k(-1)^{k-j}\binom kj\binom{8j}{10}
$$
ways to choose $10$ cards with values forming exactly a given set of $k$ values. Thus the number of combinations is
$$
\sum_{k=2}^7\binom{14-k}k\sum_{j=2}^k(-1)^{k-j}\binom kj\binom{8j}{10}=153020720928
$$
(computation) out of a total of $\binom{104}{10}=26100986351440$, so the probability for this to occur is
$$
\frac{153020720928}{26100986351440}=\frac{9563795058}{1631311646965}\approx0.00586264
$$
in agreement with Jonathan's simulations.
Answer: I don't believe your assumption is correct. If, in a final (or any other) deal, there is no single card that can be moved to another column, it may still be moved together with one or more cards that are beneath it. So the expert player will plan to leave one or more cards of the same suit and increasing order in one of the columns, to then move them together to some matching other column.
Comment: Please be more polite. The statement "Your assumption is wrong!" can be taken to be aggressive.

Losing at Spider Solitaire


Warning: session_start(): Cannot send session cookie - headers already sent by (output started at

Question: The following warning comes in login page: Its working in localhost but not in remote host
Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at  on line 8)
Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at on line 8)

index.php
<?php
session_start();
if(isset($_SESSION['usr']) && isset($_SESSION['pswd'])){
header('Location: content.php');}
?>

<form method='post' action='login.php'>
<!– in this example I link it with login.php to check the password & username–>

Username:	<input type='text' name='usr'>

Password:	<input type='password' name='pswd'>

<input type='submit' name='login' value='Login'>
<input type='reset' name='reset' value='Reset'>

</form>

content.php

Click here to Download to Resume
<?php
session_start();
if(!isset($_SESSION["usr"]) || !isset($_SESSION["pswd"])){
 header('Location: index.php');}
include 'logoff.php';
?>

login.php

<?php
session_start();
if($_REQUEST['usr']=='suman.trytek' && $_REQUEST['pswd']=='solutions'){
$_SESSION['usr'] = 'suman.trytek';
$_SESSION['pswd'] = 'solutions';
header('Location: content.php');
}
else{
header('Location: index.php');
}
?>

Comment: In my case I had to set the file encoding without BOM.
Comment: Find answer here : http://stackoverflow.com/questions/8028957/how-to-fix-headers-already-sent-error-in-php
Comment: its  due to  multiple header location send  so you can use at the top after <?php   ob_start();
Answer: Move the session_start(); to top of the page always.
<?php
@ob_start();
session_start();
?>

Comment: Check that you aren't saving with BOM (also called a Unicode Signature). I tried everything and BOM was the problem. This is common if you're using UTF-8 files.
Comment: Awesome. It works within a single moment
Comment: Thanks, it worked. I was trying this for a while.
Answer:
session_start() must be at the top of your source, no html or other output befor!
your can only send session_start() one time
by this way if(session_status()!=PHP_SESSION_ACTIVE) session_start()
Comment: http://stackoverflow.com/questions/6249707/check-if-php-session-has-already-started
Answer: You cannot session_start(); when your buffer has already been partly sent.
This mean, if your script already sent informations (something you want, or an error report) to the client, session_start() will fail.


facebook share dialog opening in new tab, not in a popup

Question: I am trying to integrate a Facebook "Share" dialog with the SDK and have the following at the start of the body tag:

Then, as a test link I have:
Test Facebook Link

The problem is that this opens in a new tab, when it should really be opening in a "dialog" window. What am I doing wrong?
Answer: you want:

or

refer to: https://developers.facebook.com/docs/plugins/share-button/
The Facebook JavaScript basically swaps this out for it's own HTML
Comment: is there any way to open in new window, in your method?


Counterpart to regression equivariance in logistic regression?

Question: Let $T(y_i,\pmb x_i)$ be a regression estimator (of the scalar $y_i$ unto
the $p$-vector $\pmb x_i$). When $T$ is the usual LS estimator and $\nu\in\mathbb{R}^p$, we have that:
$$T(y_i+\pmb x_i'\pmb\nu,\pmb x_i)=T(y_i,\pmb x_i)+\pmb\nu$$
This property is called regression equivariance and plays much the same
 role, in the linear regression context, as translation equivariance does
in the context of multivariate estimators.
I was wondering whether there is a similar property (equivariance to a form of
translation) for logistic regression.
Answer:
In linear regression there exist two other types of equivariance: one about adding a linear function to the response ('regression equivariance') and one about multiplying the response by a constant factor ('y-scale equivariance'), but these obviously do not apply to logistic regression.

Page 6 of the following document:
http://www.stoch.uni-bayreuth.de/de/CHRISTMANN/Christmann_files/ChristmannRousseeuw_wemel.pdf
The paper studies a different type of equivariance (page 6 as well):

A property shared by all logistic regression estimators is $x$-affine equivariance.


Gitk doesn't show full diff

Question: Say I have a repository repo with two folders:

foo
bar

Say I want to see all commits in folder foo. I type gitk -- repo/foo and voilá, there they are.
Problem: All commits displayed in the graphical output silently omit any file that resides outside of foo, say, in bar.
How can I make gitk only display commits for a directory, but yet show the full changelog of a commit?
Comment: I was hoping the option `--full-diff` would work, but it doesn't appear to.
Answer: The simplest way is probably to click on View and then in the context menu, choose All files (vs command line, which goes back to the restrictions).  Note that the set of selectable commits will change as well, but you will still be on the commit you selected.
(You can also add a new view; each view can have its own selected branches, trees, and so on.)
Comment: This is a little tedious, since I'll now get a list of *all* commits in the repo, but at least I can switch it back manually.

Gitk doesn't show full diff


When combining a mechanical and digital manual into a single organ, how would you handle the difference in delay?

Question: When I combine 2 organ manuals, a mechanical and an electronical one into a single instrument, how would you setup the delay from the position of the organ player?
Let's assume the mechanical manual has an average delay of 200ms between pressing down a key and when the sound can be heard. Would you setup the digital manual to have roughly the same amount of delay or as little as possible?
I assume both sound sources are nearly in the same location.
Comment: Part of this will come down to whether or not you want them to sound at the same time or not. I can see reasons why you might want one before the other - for certain effects.
Comment: Surely it would depend on the size of the hall and the location of the pipes and/or speakers, wouldn't it?
Comment: @phoog thanks, I improved my question to clarify this
Answer: The best way to do this would be to make the delay from the electronic keyboard controllable so the player can choose whether to have a delay and if so, how much.
Answer: You might delay the electronic component a bit, yes.   But it won't need to be as much as 200ms.  A mechanical ('tracker action') organ actually has less delay than you might imagine.
https://www.ingentaconnect.com/content/dav/aaua/1968/00000020/00000004/art00003
The disadvantage to this classic type of mechanism is that the keys can be heavy, and everything needs to be quite close to the console.
150 years ago pneumatic action was popular.  It enabled larger instruments, and suited the Victorian taste for the bombastic. A disadvantage was sluggish response.
https://en.wikipedia.org/wiki/Tubular-pneumatic_action#Decline_of_usage
Today, tracker action is back in fashion, with electro-mechanical action where distance makes it necessary.  Delay IS an issue, but it's acoustic rather than mechanical.  Organs tend to inhabit large buildings, sections of a large organ may be mounted some distance from the console for dramatic or architectural effect. sound takes time to travel, and what the organist hears may be more reverberant than direct sound.
or headphones
Maybe organists should be provided with nearfield monitors, fed from microphones close to each rank of pipes!   In practice they just hit the keys in time and manage to isolate their brains from the acoustic feedback!
Organ is not the only instrument where the player has to (often automatically and subconsciously) 'play early'.  But not many have to deal with the delay from a unit at the other end of a sizeable church  AND the earlier sound from more local pipes!
Also see:
How does a pipe organist deal with latency or delay?
Comment: The organ was built in 1893 and uses "conical windchests with pneumatic tract", if my translation is correct. "Rein-pneumatische kegellade" is the dutch or german definition. The electronic stops are now in use for about a year and they work just fine with the mechanical stops. I assume the builders matched the delays.
Answer: Don't you have your problem backwards?  A mechanical keyboard opens the valves to the pipes.  Its action is as fast as possible.  Pneumatic and/or electric systems are the ones that introduce latencies due to intermediate mechanisms.  They are avoided in modern organs because they remove the fine control of the player over the key attack.  So unless you have one of the pneumatic monstrosities popular in the 19th century, there will be no need for delay.  If you do have one of those, the delay will very much depend on just what kind of organ you have and just what kind of pneumatic lines have been laid over what distance.  There is no general advice suitable then.


object not iterable with inputfile

Question: I am basically trying to update a line in saved files with new updated number but it leaves only one line in the file. It feels like its overwriting over entire file rather than updating it. I looked at other questions here, and although they gave me right module to use I can't seem to figure out the problem I am having.
unique = 1
for line in fileinput.input('tweet log.txt', inplace=1):
    if tweet_id in line:  #checks if ID is unique, if it is not, needs to update it
        tweet_fields = line.split(';')
        old_count  = tweet_fields[-2]
        new_count = 'retweet=%d' % (int(tweet_retweet))
        line = line.replace(old_count, new_count)
        print line
        unique = 0
if unique == 1:          #if previous if didn't find uniqueness, appends the file
    save_file = open('tweet log.txt', 'a')
    save_file.write('id='+tweet_id +';'+
                    'timestamp='+tweet_timestamp+';'+
                    'source='+tweet_source+';'+
                    'retweet='+tweet_retweet+';'+'\n')
    save_file.close()

I feel like this has a very easy solution but I am clearly missing it.
Thanks in advance!
Answer: I think the issue you're having is due to your conditional in the loop over the input. When you use fileinput.input with the inplace=1 argument, it renames the original file adding a "backup" extension (by default ".bak") and redirects standard output to a new file with the original name.
Your loop is only printing the line that you're editing. Because of this, all the non-matching lines are getting filtered out of the file. You can fix this by printing each line you iterate over, even if it doesn't match. Here's an altered version of your loop:
for line in fileinput.input('tweet log.txt', inplace=1):
    if tweet_id in line:
        tweet_fields = line.split(';')
        old_count  = tweet_fields[-2]
        new_count = 'retweet=%d' % (int(tweet_retweet))
        line = line.replace(old_count, new_count)
        unique = 0
    print line

The only change is moving the print line statement out of the if block.

object not iterable with inputfile


Notepad++ is recognizing my html.erb files as javascript files! It's messing up my syntax highlighting!

Question: This is really annoying...it really is messing up my syntax highlighting...
I think it suddenly happened after I deleted one of my javascript_include_tag statements and saved...suddenly the highlighting changed.
This all happened around the time I created my first js.erb file...
Oh yeah: It was working before!!!  I have "erb" already added as a file association/extension to html files...but for some reason, html.erb files are suddenly getting interpreted as javascript files! like, in the bottom left, it says what type of file you are viewing, and when I have an html.erb file open it says "javascript file" which is absurd...it used to say html erb...
Comment: Or Visual Web Developer from Microsoft, it's free as long as you register. Great editor.
Answer: You can configure Notepad++ to recognize an .erb (.html.erb or .js.erb) file and associate it with a given language (html).

In the menu bar, go to Settings > Style Configurator...
In the list labelled "Language:", scroll down to HTML.  Click on it
Beneath the lists for Language and Style, there should appear two fields: Default ext and User ext.  Enter 'erb' in the User ext field.
Click Save & Close

Now when you open a file with the .erb extension (incl. .js.erb), Notepad++ will automatically apply syntax highlighting for HTML.
Answer: I figured out the problem myself.  Since Rails 3 uses this new js.erb file, at one point, I went to the style configurator and added "erb" as an extension option under "Javascript."  I had already done this for html so html.erb is recognized as html, so apparently notepad++ has this bug in it b/c once I added "erb" to Javascript all html.erb began getting recognized as JS files.  Removing that "erb" to Javascript in the style configurator fixed the problem. :)
Answer: Check the post here:

http://www.thekua.com/atwork/2009/07/file-associations-in-notepad/

It allows you to change the associations.
Comment: No, I get that...the problem is that notepad++ won't recognize the files correctly...it recognize html erc as javascript... :/
Comment: I don't have Notepad++ right now to confirm, but from what I remember if you go and set up the file association for `.erb` (in the picture from the link I posted, input this in User ext: field), you can specify which language it should be "recognized" as. You can add multiple extensions (separate them by space) that need to be recognized as JavaScript. E.g. if you add `js erb` in the User extension text box, it will "recognize" `.js` and `.erb` as JavaScript files.


std::string += operator cannot pass 0 as argument

Question: std::string tmp;
tmp +=0;//compile error:ambiguous overload for 'operator+=' (operand types are 'std::__cxx11::string {aka std::__cxx11::basic_string<char>}' and 'int')
tmp +=1;//ok
tmp += '\0';//ok...expected
tmp +=INT_MAX;//ok
tmp +=int(INT_MAX);//still ok...what?

The first one argues that passing integer as argument, right? Why others passes compilation?I tested on Visual C++ and g++, and I got the same result above. So I believe I miss something defined by standard. What is it?
Comment: `int` will be converted to `char`. but for `0` its difficult to say whether its `NULL` or `int 0`
Answer: The problem is that a literal 0 is a null pointer constant.  The compiler doesn't know if you meant:
std::string::operator +=(const char*);  // tmp += "abc";

or
std::string::operator +=(char);         // tmp += 'a';

(better compilers list the options).
The workround (as you have discovered) is to write the append as:
tmp += '\0';

(I assume you didn't want the string version - tmp += nullptr; would be UB at runtime.)
Comment: Yes.  `char` is a integral type, and an integer is implicitly convertable to char.  `+=(char)` is the overload that is being invoked in *all* the non-ambiguous cases.
Comment: Should the compiler really consider `+=(char)`?
Answer: The 0 literal is implicitly convertible to all pointer types (resulting in their respective null pointer constants). Therefore it results in two equally valid conversion sequences for matching std::strings appending operator.


Binary Classification: changing the notion of "positive label"

Question: Perhaps more logical/philosophical rather than math question. In binary classification setting, classes are most often not symmetrical and one of them is considered to be "positive" or "success", while other one is "negative" or "failure". This fact is used for classification with skewed posterior probability threshold, it defines such notions as true positives, false negatives, etc and corresponding evaluation measures.
Now the question - does the notion of success class belong to the model, i.e. once you have fitted the model based on the training features/response - success class must be defined at this point and changing it afterwards is a violation? Or one could have a fitted model and still change the notion of the success class - say for predicting new data? At this point the training data/labels are N/A, and classifier has done its job - so does it mean that the success class notion should not/ could not be changed after this point?
Comment: I don't understand the question. Can you give a concrete use case where you would want to change the classes? The way I interpret the question, you want to make a model to distinguish, say, cats and dogs and then somehow use it to recognize apples. If so, that doesn't make a lot of sense.
Comment: I suppose, just tentatively, that it won't violation, and you don't have to re-fit the model, only to "invert" some its ouptut figures accordingly. But I suppose it so only for binary, univariate situation. If classification is multi-class or is mutivariate binary - it will be different.
Comment: I still don't see the difference. You make a model for a given target class and then use it for something else. Intuitively, that cannot work well.
Comment: @ttnphns Not sure why you mention "univariate/multivariate" settings and how they affect this matter. Regarding the "re-fitting" - yes, success class shouldn't affect the fitting part at all... But the necessity of "inverting" something if the success is changed implies that the success class must be the part of the model - is that what you've meant?
Comment: @MarcClaesen - I don't mean to change the class labels, only the notion of what is being considered as a success class/ case/ positive label, whatever you call it.
Answer: The model does not know what "successful" and "unsuccessful" mean. All the model knows is the $0$$/$$1$ encoding you pass to it (which has an equivalence with a $\pm1$ encoding, if you prefer that). Consequently, if you change what $0$ and $1$ mean, the model is ignorant of this and keeps doing what you trained it to do.
Perhaps think of it this way: you train a regression model that makes extremely accurate predictions of distances in meters, but then you realize that your American customer wants the output in feet. Do you use the model output and tell your customer that is how many feet you predict (and be off by a factor of three-and-a-bit), or do you convert to feet?


Is there a way to connect to port 80 on my VPS and have my VPS forward that to another port?

Question: I'm not sure if I'm using the correct term.
Where I work the only open port is port 80. I'm trying to stream music over internet radio, which uses port 8080. Is there a way to have my VPS connect to the stream on port 8080, and then have it redirect the stream to port 80 on itself, so I can connect to it? Or is what I'm saying impossible?
Answer: or you can setup mod-proxy on apache and forward traffic to many different sites [ radio stations ? ] - as long as they use http to steram music.
simple setup would look like this:
<VirtualHost *:80>
#    ......
    ProxyPass  /radio1/a.ogg  http://radio.hbr1.com:19800/trance.ogg
    ProxyPass  /radio2/a.ogg  http://radio.hbr1.com:19800/tronic.ogg
    ProxyPass  /radio3/a.ogg  http://radio.hbr1.com:19800/ambient.ogg
    ProxyPass  /radio4/ http://voxsc1.somafm.com:8388
</VirtualHos>

then - at the office - you just turn on your music player and listen to http://your.vps/radio1/a.ogg or http://your.vps/radio4/ etc
this is especially useful if you have proxy filtering traffic [ and eg preventing attempts to tunnel ssh over port 80 ].
this approach is also much more 'it security policy' friendly...  while ssh - not so much...
but preferably contact your IT, get approval or at least keep your winamp updated
Answer: You can use an SSH tunnel.
http://oldsite.precedence.co.uk/nc/putty.html
Forward your VPS port 80 to destination port 8080. Then when you connect to port 80 on your VPS it's as if you had connected directly to the destination.
You can create it from your client machine if you can ssh to your VPS. Otherwise, you can just do a tunnel on the VPS and keep it alive before you go to work. Make sure you allow it to "Accept connections from other hosts"
Answer: If I understand what you are asking, you can do this with source and destination NAT for iptables as well.  This link explains the iptables commands.
Comment: Depending on the VPS, sometimes it is quite troublesome to configure iptables on them.
Answer: By far the easiest way is to set up xinetd or similar to 'redirect' all your connections. You won't need to touch your web-server that way. Do something like this for xinetd.
service webcache
{
  flags = REUSE
  socket_type = stream
  wait = no
  user = root
  redirect = localhost 80
  log_on_failure += USERID
}

Restart xinetd and you are done.


French accented characters not saving to database

Question: I have created a module that reads in a csv file that has french accented characters in it to create nodes from. The creation of the nodes seems to work fine but when I execute the node_save() command I get the following error:
An AJAX HTTP error occurred. HTTP Result Code: 500 Debugging information follows.
Path: /batch?id=55&op=do StatusText: Service unavailable (with message)
ResponseText: PDOException: in field_sql_storage_field_storage_write()
(line 494 of /var/www/html/modules/field/modules/field_sql_storage/field_sql_storage.module).

The special character I am having problems with is é character (however I am sure other accented characters will cause me grief as well).
I thought this was an encoding issue and checked the database encoding on the tables - all tables are set to UTF8. I believe that this is the correct encoding and should work (however I am no database expert).
I tried using the following code:
$encodedval = mb_check_encoding($val, 'UTF-8') ? $val : utf8_encode($val);

Which seems to help but still gives the same error after 300 items are read in (there are 3000 items that need to be imported). During the importing, I am Geo-referencing the nodes, so could this be Google killing the look-ups after so many hits?
I am at a loss and would appreciate if anyone could shed some light as to what might be the issue.
Comment: You may require utf8mb4 rather than straight utf8.
Answer: Both suggested solutions above are good things to check when trying to solve this problem.
In my particular case, using the fgetcsv command. It silently chokes on files that are not UTF-8 encoded and contains accented characters. To fix this problem I had to implement the file read function as follows:
while (($line = fgets($file_handle)) !== FALSE) {
  // Ensure the line we read is encoded properly
  $value = mb_check_encoding($line, 'UTF-8') ? $line : utf8_encode($line);
  $data = str_getcsv($value);
  // process the data as normal
}

This fixed my issue.
Answer: Have you tried to save your module file in another encoding format?
I'm usually having the same issues as my files are default to AINSI.
After converting the file to UTF-8 I have no more issues.
By doing so you will have to remove your utf8_encode() calls to avoid double encoding.
Answer: I've imported thousands of Spanish-language nodes using the Feeds module; so I would indeed suspect that something is going wrong in the georeferencing, especially with the "Service unavailable" message. Does Google return something human-readable? If so, I suggest writing out the responses to a log file somewhere, and see if something goes wonky after 300 requests.


Comparing series with convergent series

Question: Prove that if the series $x_{n}$ converges then series $(x_{m}+x_{k})$ converges, where $k=2n+1$ and $m=2n$.
So if i show that the partial sum of $x_{n}$ is convergent how does this have to compare with the partial sum of the other series??
Do I have to use the limit definition for the partial sums?
Also is there an example where the converse is invalid? (only hint is enough for this part!)
Please help!
Comment: Write out the first few terms of each. From what I can tell they're the same series, just being written two terms at a time in the second case.
Comment: Hint about the converse: try x(2n)+x(2n+1)=0 for every n.
Comment: *Alternating series* has a very specific meaning (alternation in sign, **plus** $|a_{n+1}|\le |a_n|$ **plus** $\lim a_n=0$. You will want your terms to alternate in sign, but likely want the $|a_n|$ not to get small.
Comment: that sounds like an alternating series right??
Answer: The problem here says:
Suppose $x_0 + x_1 + x_2 + x_3 + x_4 + x_5 + x_6 + x_7 + x_8 + x_ 9 + \cdots$ converges.
Prove: $a_0 + a_1 + a_2 + a_3 + a_4 + \cdots$ converges, where $a_n = x_{2n} + x_{2n + 1}$.
(For example, $a_3 = x_6 + x_7$.)
In particular, the $n$th partial sum of the $a_n$ series is the $(2n+1)$st partial sum of the $x_n$ series.
So: yes, you can use the "limit definition for partial sums" (isn't this how you defined convergence of an infinite series?) to prove that the $a_n$ series converges.
For the converse, let $x_n = (-1)^n$.
Does $\sum x_n$ converge? Does $\sum a_n$ converge?
Comment: thankyou very much! i appreciate ur help :))

Comparing series with convergent series


what is use of abstract class in android

Question: what is the use of abstract class in android.
For code reusablity I can create base class that contains common method and it extended in other class.I would like to know what is the exact use of abstract class in android
<code>public class Base{

   public void test(){
     System.out.prinltn("test");
   }

}

public class main extends Base{
    test();
}
</code>
Comment: you can outsource code of classes wich got same elements and keep your code withour duplicates. `DRY-principle`.
Please also have a look on the `SOLID-Principle` when you got basic questions like this. It´s a kind of architectre.
Answer: When there is some part of the implementation (let's call it A)  which you want to be provided by the sub classes (in future as per requirements) and also there is some comman part of the implementation shared by all sub classes (let's call it B). Now part A is not known as how to be implemented as it will depend on future requirements hence it's best to have it as abstract. By having abstract methods all the sub classes are forced to provide the implementation.
Abstract class can contain all the common states and methods and can abstract the methods which will have different implementation as per the sub class implementation. The common methods also can be override if needed.
Also you can refer template design pattern, it's intent and implementation as it is a very good example of usuage of abstract class.
Comment: can you provide the concepts in simple manner . It helps me to understand the concept
Comment: so the answer will be avoid the object creation for base class. i would prefer abstract class.Is my assumption is correct?
Comment: Suppose you are writing a class which has a behaviour whose implementation you do not know and want the sub classes to decide the implementation. Now of course as one of the behaviour does not have implementation hence you would not like the objects of such a class to exist (abstract class can not be instantiated). Read factory pattern and template pattern, they will be helpful in seeing usuage of abstract class. I will try to edit my answer to provide some more details later