text:
Q: Motivation and examples for ramification I started learning algebraic number theory, but it seems like all the sources I had are too abstract, giving me difficulty understanding the concept and tripping me up frequently. For today it is ramification (for a prime ideal).

Can someone explain to me, with concrete example, the motivation and the intuition behind concept such as "ramification index", "ramified/unramified", "totally ramified", and "tamely/wildly ramified"?
Also, I saw something about ramified character in the context of Hecke's thesis, not sure if it have anything to do with this, if it does, can someone point out the relevance too?

Thank you very much.

A: Ok, this is certainly a non-trivially complicated question.
I chose to give some sort of geometric intuition. I'm not totally sure this is what you were after, but hopefully it's of some use to you!

Geometric prelude
So, the best place to start thinking about ramification, is in terms of maps of Riemann surfaces. While this may seem unrelated at first, bear through it, and I promise (hopefully!) it will make sense at the end.
So, a Riemann surface is something like a one-dimensional manifold, but instead of our space 'locally looking like an open subset of $\mathbb{R}$' it locally looks like an open subset of $\mathbb{C}$. Moreover, whereas 'locally looking like' in the context of real manifolds is meant in the smooth (i.e. $C^\infty$) sense, in the case of Riemann surfaces, it's meant in the holomorphic (i.e. analytic) sense.
Good examples of Riemann surfaces are things like the sphere $S^2$ for which at each point $p\in S^2$ we can think of the sphere as locally looking like $\mathbb{C}$. Moreover, as we change these charts (local ways of looking like $\mathbb{C}$), the coordinates they give vary in a holomorphic way. Another example would be the torus $\mathbb{C}/\Lambda$ (for $\Lambda\subseteq\mathbb{C}$ a lattice).
Now, if we have two Riemann surfaces $X$ and $Y$, we can look at holomorphic maps $f:X\to Y$. Given two points $x\in X$ and $y\in Y$ we can choose charts around $x$ and $y$, so homeomorphisms $U\to X$ (whose image contains $x$), and $V\to Y$ (whose image contains $y$), where $U,V\subseteq \mathbb{C}$ are open. We can then use these to think (locally around $x$/$y$) of $f$ as being just a holomorphic map $f:U\to V$.
Now, it's a common fact from the theory of one complex variable (sometimes called the 'local normal form theorem'), that says that there exists a unique integer $n$ such that for sufficiently small neighborhoods $W$ of $x$, the mapping $f:W\to V$ looks like (i.e. up to pre/post composition with a biholomorphism is) the mapping $z\mapsto z^n$ from the disc $D(0,1)$ to $\mathbb{C}$;
Now, let's think about what the $n^\text{th}$-power map $D(0,1)\to\mathbb{C}$ looks like. Well, if we write an element of $D(0,1)$ as $z=r e^{i\theta}$, for $r<1$ we see that the $n^\text{th}$-power map send this to $r^n e^{i n\theta}$. So, it shrinks the length of the vector $z$, and also multiples its angle by $n$. In particular, for $r\ne 0$, we see that a $w= r e^{i\theta n}\in D(0,1)$ has exactly $n$ preimage points: $r^{\frac{1}{n}}e^{i \omega}$, where $\displaystyle \omega=\frac{2\pi \theta}{m}$, for $m=1,\ldots,n$.
However, look what happens when $r=0$ (i.e. when $z=0$)--the $n^{\text{th}}$-power map does nothing. If you think about the previous paragraph as saying that the $n^{\text{th}}$-power map causes the disc to 'cover itself $n$ times', and each covering is a 'sheet', then all of these sheets meet at precisely one place--the fixed point $0$. So, if $n>1$, then somehow $0$ is this degenerate point which stops the $n^{\text{th}}$-power map from being precisely a $n$-sheeted covering of itself. It ties all the sheets together, and since it's in multiple sheets, 'counts' for more than just a point, it counts for how many sheets it lies in.
Now, let's bring this back to the original context of Riemann surfaces. This local analysis tells us that for our map of Riemann surfaces $f:X\to Y$, and our points $x\in X$ and $y\in Y$, the mapping $f$ locally (around the points) looks something like some $n$-sheeted covering, here $n$ is the same as the one given to us by the local normal form theorem. But, as we said above, it's not precisely an $n$-sheeted covering (if $n>1$) since the point $x$ (which corresponds to $0$ in the disc) doesn't get covered $n$-times, it just stays stationery--it lies in $n$-sheets (opposed to the other points around it, which lie in $1$-sheet). Let's call this integer $e_x$--it's how many 'sheets' that $x$ lies inside of.
Now, why is this integer something of importance to us. Well, first and foremost, it allows us to give a very simple answer to an (otherwise complicated) question:

How many points are in $f^{-1}(y)$, for $y\in Y$?

In other words, how many points are in the preimage of a point in $Y$?
Now, taken literally, this question is hard. The answer could really be anything, and greatly depends on which point $y\in Y$ that we take. But, if we're clever, and tweak the question every so slightly, we get a much more satisfying answer.
For example, let's consider the $n^\text{th}$-power map $g:D(0,1)\to D(0,1)$ again. If we take an arbitrary point $y\in D(0,1)$, we can ask how many points are in the preimage. Well, the answer breaks into two case:
$$\# g^{-1}(y)=\begin{cases}1 & \mbox{if}\quad y=0\\ n & \mbox{if}\quad y\ne 0\end{cases}$$
But, if we use our intuition that we should count the point $0\in D(0,1)$ not just as itself, but for the $n$ sheets it's contained in, we do get a constant answer of $n$.
Said differently, instead of asking for $\#f^{-1}(y)$, let's instead ask for
$$\sum_{x\in f^{-1}(y)}e_x$$
so, we're not just asking for how many points map to $y$, but to weight these points by how many sheets there in. This makes the answer a constant number. This is a theorem you have to prove, but it's not hard. This map $X\to \mathbb{Z}$ sending $x$ to this sum can be shown to be locally constant (think about the local normal form theorem!), and so if $X$ is connected, must, in fact, be constant.
So, it clearly is nicer, and fits better the 'global properties', to not count total preimages, but these weighted preimages based on the 'multiplicities' $e_x$ of points.
Thus, the natural thing then is to study the points with multiplicity greater than $1$: $x$ such that $e_x>1$. These are the points where multiple sheets come together.
An important thing to notice is thatese points are  the points where $f:X\to Y$ is NOT an isomorphism on a neighbhorhood of $x$ (think about the local normal form theorem again!). Translating this into a form which will be more useful later, they are the points where $f$ doesn't send charts (around $x$) to charts (around $y$).
These points, these 'bad' but significant points, are called the ramification points of $f:X\to Y$.

Relation to number theory
Somewhat surprisingly, this is the motivating factor, and intuition, for the notion of ramified primes in algebraic number theory.
Just to make sure we're on the same page, let's briefly recall the setup of what ramified vs. unramified primes look like. For the sake of convenience, I'm going to assume that you're working over number fields.
So, we have an extension of number fields $L/K$. We then have associated to this an extension of Dedekind domains $\mathcal{O}_L/\mathcal{O}_K$. For any non-zero prime $\mathfrak{p}$ of $\mathcal{O}_K$, we know that $\mathcal{p}\mathcal{O}_L$ (by integrality), and so we can factor this ideal as:
$$\mathcal{p}\mathcal{O}_L=\mathfrak{P}_1^{e_1}\cdots\mathfrak{P}_m^{e_m}$$
We say that $\mathfrak{P}_i$ is ramified if $e_i>1$.
Now, how are we going to relate this to the geometric setting of maps between Riemann surfaces? Well, the go between is the subject called algebraic geometry, which allows us to think about the set of prime ideals of $\mathcal{O}_L$, and the set of prime ideals of $\mathcal{O}_K$, as geometric objects unto themselves.
It isn't important if you are familiar with algebraic geometry, as long as you're willing to take (on faith) two things. To each ring $R$ (such as $\mathcal{O}_K$ or $\mathcal{O}_L$) a geometric object $\text{Spec}(R)$, and to each ring map $f:R\to S$, an associated map of geometric objects (notice the switch in direction!) $\text{Spec}(S)\to\text{Spec}(R)$--on points, this map just takes a prime $\mathfrak{p}$ of $S$ to the prime $f^{-1}(\mathfrak{p})$ of $R$.
So, now to the inclusion of number rings $\mathcal{O}_K\hookrightarrow\mathcal{O}_L$, we get an induced map of geometric spaces $\text{Spec}(\mathcal{O}_L)\to \text{Spec}(\mathcal{O}_K$. So, now we're in a setup somewhat similar to the case of Riemann surfaces--a map between geometric objects. So, let's do what we did there.
Fix a point $\mathfrak{p}$ of $\text{Spec}(\mathcal{O}_K)$, and let's ask about the set of points in the preimage of $\mathfrak{p}$ under the map $\text{Spec}(\mathcal{O}_L)$. If you think about this for a minute, you'll see that the set of preimage points is EXACTLY the set $\{\mathfrak{P}_i\}$ of primes which divide $\mathfrak{p}\mathcal{O}_L$.
So, we can start asking about how many points are in the preimage of some random $\mathfrak{p}$. Just as before, the answer is hard to get at. There is no satisfactory/uniform way to answer this question as stated. And, moreover, just as before, this is because the 'true answer' comes from not counting literal points in the preimage, but counting them weighted by how many 'sheets' they lie in. As you may have already deduced, these points which are weighted greater than $1$ (the amount contributed just by them being a point), are precisely the primes over $\mathfrak{p}$ that ramify!
How can we connect this notion of ramified prime to the one above though--why are they intuitively connected? Well, let's first do what we did above, and zoom in on the point $\mathfrak{p}$ and one of its preimage points $\mathfrak{P}_i$. In algebraic geometry, this corresponds (see here for some intuition) to localizing our rings at the respective primes. Thus, we're looking at the mapping $(\mathcal{O}_K)_\mathfrak{p}\to (\mathcal{O}_L)_{\mathfrak{P}_i}$.
Now, before, once we shrunk the neighborhoods around the points of our Riemann surfaces small enough, we took charts, and then asked about questions relative to these charts. Now, the objects $\text{Spec}(\mathcal{O}_K)$ and $\text{Spec}(\mathcal{O}_L)$ are '$1$-dimensional' (if you know commutative algebra, this is just the fact that the rings $\mathcal{O}_L$ and $\mathcal{O}_K$ are one-dimensional). So, charts should be like 'one map', which locally dictates the behavior of the space. For us, a chart of $\text{Spec}(\mathcal{O}_K)$ at $\mathfrak{p}$ will correspond to a uniformizer $\pi$ of $(\mathcal{O}_K)_\mathfrak{p}$, and similarly, a chart of $\text{Spec}(\mathcal{O}_L)$ at $\mathfrak{P}_i$ will be a uniformizer $\varpi$ of $(\mathcal{O}_L)_{\mathfrak{P}_i}$ (while this may not mean anything to you, this is more than just an analogy--for smooth curves over $\mathbb{C}$, uniformizers literally become the charts of the analytifications).
So, we said above that what it mean for a point $x$ to be ramified, was that the map $f$ did NOT map charts at $x$ to charts at $y$. The same is true here, the chart $\pi$ at $\mathfrak{p}$ gets mapped to the object $\pi\in(\mathcal{O}_L)_{\mathfrak{P}_i}$. This element will be a chart (i.e. a uniformizer) if and only if $\mathfrak{p}$ is unramified! In fact, up to units, $\pi$ is $\varpi^{e_i}$, where $e_i$ is the same $e_i$ as above!
In fact, if you think about local rings of Riemann surfaces, that notion of ramification point is precisely the same as uniformizers not going to uniformizers. Also, the amount of sheets $e_x$ is precisely the 'power' of a uniformizer at $y$ that a uniformizer at $x$ is sent to. These situations are precisely analogous.
Thus, we should picture somehow that $\text{Spec}(\mathcal{O}_L)\to\text{Spec}(\mathcal{O}_K)$ is like a multi-sheeted covering, and, just as in the case of Riemann surfaces, the points of ramification are precisely the points where the sheets come together.
If the analogies are to hold, we'd like to also have an analogy, as alluded to above, of the fact that with our notion of ramification points, and keeping track of the number of sheets, that we can uniformly describe amount of points in the preimage. Not only do we have such a theorem, but it's one you are probably very familiar with:
$$\sum_{\mathfrak{P}\mid \mathfrak{p}}\text{ }e_\mathfrak{P} f_\mathfrak{P}=[L:K]$$
Indeed, we already noted that $\{\mathfrak{P}:\mathfrak{P}\mid \mathfrak{p}\}$ is precisely the preimage of $\mathfrak{p}$ under the map $\text{Spec}(\mathcal{O}_L)\to\text{Spec}(\mathcal{O}_K)$, and that the $e_\mathfrak{P}$ were the analogy of the multiplicity (or number of sheets) that showed up in the Riemann surface case. The only thing which is unexplained are the $f_\mathfrak{P}$, and those are a holdover of 'hidden points'. That's a whole nother story. See my answer here for a taste.

I should probably mention the things I didn't talk about. Totally ramified just means that there is one-preimage point where $[L:K]$ sheets come together. Tamely and wildly ramified is a more technical condition, which has less of a geometric flair (or, at least, not one as easily yielded by basic words in algebraic geometry).
As for the characters in Hecke's thesis, I would need you to be more specific about what type of characters they are. Are they grossencharacters, or characters of the (absolute) Galois group?


text:
Q: Latex table format for springer class While using springer latex format, i am having trouble using table in this format that works fine in elsevier and other templates besides including all required packages. So I am unable to wrap text instead getting errors for using cols and pos and many more.
I have used following in the springer journal latex template
\begin{table}[cols=4,pos=h]
    \centering
    %\captionsetup{justification=centering} %ok
    \setlength{\tabcolsep}{3pt}
    \begin{tabular*}{\textwidth}{@{}Lp{0.3\textwidth}p{0.3\textwidth}p{0.3\textwidth}@{}}

when I try its own provided table format like this

\documentclass{sn-jnl}

\begin{document}

    \begin{table}[h]%[pos=h] %cols=4,pos=h
        \begin{center}
            %\captionsetup{justification=centering} %ok
            %\setlength{\tabcolsep}{3pt}
            %\begin{tabular*}{\textwidth}{@{}Lp{0.3\textwidth}p{0.3\textwidth}p{0.3\textwidth}@{}}
            \begin{tabular}{@{}llll@{}}
            \toprule
            S.No. & Drawbacks Observed  &  Proposed Solution Protocol when Size $< 32+40 $ &  Proposed Solution protocol when Size $\ge 52+10$ \\
            \midrule
            1 & Affect of Area acceptance on high speed vehicles & speed in some order used  high speed placement scheme and observation collected in scenarios & High Speed chase \\
            2 & Affect Of color on low speed vehicles & speed in some order used  high speed placement scheme and observation collected in scenarios &   Low Speed chase    \\
            \bottomrule
        \end{tabular}
        \end{center}
    \end{table}
\end{document}

I get my table out of the page width with unwrapped text as seen in attached image.
Any help will be grateful

A: You need to employ a table environment that allows automatic line breaking in columns 2 and 3. One such environment is the tabularx environment. I would also recommend providing a bit more structure to the header row(s), in order to cut down on repititive information.

\documentclass{sn-jnl}
\usepackage{tabularx,ragged2e}
\newcolumntype{L}{>{\RaggedRight}X}

\begin{document}
\begin{table}[h] %[pos=h] %cols=4,pos=h
   \begin{tabularx}{\textwidth}{@{} l LLl @{}}
   \toprule
   S.No.
   & Drawbacks observed
   & \multicolumn{2}{c@{}}{Proposed solution protocols} \\
   \cmidrule(l){3-4}
   & & when size $< 32+40 $ & when size $\ge 52+10$ \\
   \midrule
   1
   & Affect of area acceptance on high speed vehicles
   & speed in some order used high speed placement scheme
     and observation collected in scenarios
   & High Speed chase \\
   \addlinespace
   2
   & Affect of color on low speed vehicles
   & speed in some order used high speed placement scheme
     and observation collected in scenarios
   & Low Speed chase \\
   \bottomrule
   \end{tabularx}
\end{table}
\end{document}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Differences between SQL Server stored procedure and user query We have a stored procedure that pulls information from a few different tables to display some information. This works fine.
We now want to "borrow" some of the code and I'm trying to do some dev work. When I copy the contents of the stored procedure out into a query window and run it (minus the stored procedure related stuff), it completes successfully but no results are returned - in fact #test2 is not populated. Running the same via the stored procedure returns results normally.
Code is below from the query - stored procedure is the same just with ALTER PROCEDURE and I have changed all the table names etc...
    SET ANSI_NULLS ON
    GO

    SET QUOTED_IDENTIFIER ON
    GO

    DECLARE @reportstart smalldatetime, @reportend smalldatetime

    SET @reportend = 2016-01-01
    SET @reportstart = 2016-02-01

    SET NOCOUNT ON;

    SELECT
        OPA10.[PATIENT PATHWAY IDENTIFIER], OPA10.RTTPeriod
    INTO #TEST
    FROM
        (SELECT
             PL.[PATIENT PATHWAY IDENTIFIER], PL.RTTPERIOD
         FROM
             [PATHWAY LTR] AS PL
         INNER JOIN
             [PATHWAY LTR] AS PL2 ON PL.[PATIENT PATHWAY IDENTIFIER] = PL2.[PATIENT PATHWAY IDENTIFIER]
                                  AND PL.LTRSequence = PL2.LTRSequence  +1
         INNER JOIN
             [PATIENT PATHWAY] AS PP ON PL.[PATIENT PATHWAY IDENTIFIER] = PP.[PATIENT PATHWAY IDENTIFIER]
         WHERE
             PL.ActivityType = 'OPD'
             AND PL.LTRSequence = 3
             AND (PL2.OPDisposal IN ('05', '08')
              OR PL2.ActivityStatus IN ('DNA', 'CND'))) OPA10

    SELECT DISTINCT
        [PATIENT PATHWAY].[LOCAL PATIENT IDENTIFIER],
        [RTT PERIOD].[PATIENT PATHWAY IDENTIFIER], pd.Surname,
        [RTT PERIOD].[RTT PERIOD ID WITHIN PATHWAY],
        CAST([RTT PERIOD].[REFERRAL TO TREATMENT PERIOD START DATE] AS DATE) as 'RTT START DATE',
        CAST([RTT PERIOD].[REFERRAL TO TREATMENT PERIOD END DATE] AS DATE) AS 'RTT END DATE',
        [RTT PERIOD].[RTT SPECIALTY],
        CAST(DATEADD(D,126,[RTT PERIOD].[REFERRAL TO TREATMENT PERIOD START DATE])AS DATE) AS 'BREACH DATE',
        'BREACH FLAG' = CASE
                           WHEN CAST(DATEADD(D, 126, [RTT PERIOD].[REFERRAL TO TREATMENT PERIOD START DATE]) AS DATE) < CAST([RTT PERIOD].[REFERRAL TO TREATMENT PERIOD END DATE] AS DATE)
                              THEN 'NOT WITHIN'
                              ELSE 'WITHIN'
                        END,
        --DATEDIFF(DD, CAST([RTT PERIOD].[REFERRAL TO TREATMENT PERIOD START DATE] as date),
        --CAST([RTT PERIOD].[REFERRAL TO TREATMENT PERIOD END DATE] AS date)) AS UNADJWAITDAYS,
        [RTT PERIOD].[RTT CLOCK STOP ACTIVITY],
        [RTT PERIOD].[RTT CLOCK STOP ACTIVITY STATUS],
        [RTT PERIOD].[RTT COMMISSIONER], [RTT PERIOD].[SHARED BREACH],
        [PATIENT PATHWAY SITE].[18WKSITE],
        [MERGE SPECIALTY].[DESCRIPTION],
        [MERGE SPECIALTY].[MERGE SPECIALTY],
        --,WLREMOVAL.Comment
        --,[PATHWAY LTR].[InternalPatientNumber(iSOFT-PAS)]
        --,[PATHWAY LTR].[InternalEpisodeNumber(iSOFT-PAS)]
        --,[PATHWAY LTR].EpsActvDtime
        [PATHWAY LTR].LTRSequence,
        [PATIENT PATHWAY SITE].[18WK provider]
    INTO
        #TEST2
    FROM
        [RTT PERIOD]

    /*  ************************
        THIS CODE HAS BEEN ADDED TO GET THE SITE FLAG
        ************************/
    INNER JOIN
        [PATIENT PATHWAY SITE] ON [RTT PERIOD].[PATIENT PATHWAY        IDENTIFIER] = [PATIENT PATHWAY SITE].[PATIENT PATHWAY IDENTIFIER]
    /****************************************/

    INNER JOIN
        [PATIENT PATHWAY] ON [RTT PERIOD].[PATIENT PATHWAY IDENTIFIER] = [PATIENT PATHWAY].[PATIENT PATHWAY IDENTIFIER]
    INNER JOIN
        [PATHWAY LTR] ON [RTT PERIOD].[PATIENT PATHWAY IDENTIFIER] = [PATHWAY LTR].[PATIENT PATHWAY IDENTIFIER]
                      --and [RTT PERIOD].[RTT PERIOD ID WITHIN PATHWAY] = [PATHWAY LTR].RTTActivityID
                      --and [PATHWAY LTR].RTTActivityID = 1
                      AND [PATHWAY LTR].EpsActvDtime = [RTT PERIOD].[REFERRAL TO TREATMENT PERIOD END DATE]
    --left outer join [iSOFT-PAS_Landing].dbo.WLREMOVAL on
       --[PATHWAY LTR].[InternalPatientNumber(iSOFT-PAS)] = WLREMOVAL.InternalPatientNumber
      --and [PATHWAY LTR].EpsActvDtime = WLREMOVAL.EpsActvDtimeInt
    INNER JOIN
        [iSOFT-PAS_Landing].dbo.PATDATA as PD ON [PATIENT PATHWAY].[InternalPatientNumber(iSOFT-PAS)] = PD.InternalPatientNumber
    LEFT OUTER JOIN
        [18-Weeks].dbo.[MERGE SPECIALTY] ON [MERGE SPECIALTY].[RTT SPECIALTY] = [RTT PERIOD].[RTT SPECIALTY]
    WHERE
        ([RTT PERIOD].[REFERRAL TO TREATMENT PERIOD END DATE] >= @reportstart)
        AND ([RTT PERIOD].[REFERRAL TO TREATMENT PERIOD END DATE] < @reportend )
        AND ([RTT PERIOD].[RTT PERIOD TYPE] = 'N')
        AND ([RTT PERIOD].[REFERRAL TO TREATMENT STATUS AT END OF PERIOD]) <>'33'
        AND ([RTT PERIOD].[RTT CLOCK STOP ACTIVITY]) <> 'opd'
        AND ([PATHWAY LTR].[ActivityType]) <> 'WADD'
        AND ([RTT PERIOD].[RTT PERIOD ID WITHIN PATHWAY]) =1
        --and [PATIENT PATHWAY SITE].[18WK provider]='RN700'
        OR ([RTT PERIOD].[REFERRAL TO TREATMENT PERIOD END DATE] >= @reportstart)
        AND ([RTT PERIOD].[REFERRAL TO TREATMENT PERIOD END DATE] < @reportend)
        AND ([RTT PERIOD].[RTT PERIOD TYPE] = 'N')
        AND ([RTT PERIOD].[REFERRAL TO TREATMENT STATUS AT END OF PERIOD]) <>'33'
        AND ([RTT PERIOD].[RTT CLOCK STOP ACTIVITY]) <> 'opd'
        AND ([PATHWAY LTR].[ActivityType]) = 'book'
        AND ([RTT PERIOD].[RTT PERIOD ID WITHIN PATHWAY]) = 2
        --and [PATIENT PATHWAY SITE].[18WK provider]='RN7

   SELECT t2.*
   FROM #TEST2 AS T2
   LEFT OUTER JOIN #TEST AS T ON T2.[PATIENT PATHWAY IDENTIFIER] = T.[PATIENT PATHWAY IDENTIFIER]
                               AND T2.[RTT PERIOD ID WITHIN PATHWAY] = T.RTTPeriod
   WHERE
       t.[PATIENT PATHWAY IDENTIFIER] IS NULL

   select * from #TEST
   select * from #TEST2

        -- drop table #TEST2
        -- drop table #TEST

A: You need to quote date with ':
DECLARE @reportstart smalldatetime, @reportend smalldatetime;

SET @reportend = '2016-01-01';
SET @reportstart = '2016-02-01';

Otherwise you will get implicit conversion from INT to DATE which is  year 1905.
LiveDemo

It works similiar to this:
SET @reportend = 2016-01-01;
--SET @reportend = 2014   -- int
--SET @reportend = DATEADD(d, 2014,'1900-01-01')
--SET @reportend = '1905-07-08 00:00:00'

I highly doubt that you have data from 1905


text:
Q: Username mapping, want to choose the backup server when primary server is down Struggle with a batch-netlogon script for choosing the correct server when the main is down for maintance.
This is a part from the script:
:common
IF EXIST "\\topnet\users\%username%\." goto :topnet else :topserv
:topnet
net use U: \\topnet\Users\%USERNAME%
net time \\topprimo /Set /Yes
goto end
:topserv
net use U: \\topserv\Users\%USERNAME%
net time \\topprimo /Set /Yes
goto end

If the \\topnet server is offline the script must detect that, so it will be connected to the \\topserv
topnet is a domain controller 2003 and topserv is a BackupNAS.
The user maps are live synchronized from topnet -> topserv.


text:
Q: How to convert std::string to LPVOID I need convert std::string to LPVOID for create PIMAGE_DOS_HEADER.
Already i have tested some casting but my PE Header isn't right.
std::ifstream file;
file.open("C:/testDLL.enc");
std::string data;
file >> data;
file.close();;

std::string decrypted = decrypt(data);

LPVOID lpData = static_cast<LPVOID>(&decrypted[0]);

//LPVOID lpData = reinterpret_cast<LPVOID>((char*)decrypted.c_str());
//LPVOID lpData = (char*)decrypted.c_str();

PIMAGE_DOS_HEADER pDH = (PIMAGE_DOS_HEADER)lpData;

Thanks for helps.

A: string decryptempty(string data)
{
    // I dont know your decrypt & encrypt functions..

    return string(data);
}
int main() {
    std::ifstream file;
    file.open("C://testDLL.dll",ios::binary);
    std::string data;
    file >> data;
    file.close();

    string decryptedstr = decryptempty(data);
    LPVOID ptr = &decryptedstr[0];
    PIMAGE_DOS_HEADER pDos = reinterpret_cast<PIMAGE_DOS_HEADER>(ptr);

    printf("e_magic : %02x\n", pDos->e_magic);
    printf("string buffer : %p\n", ptr);
    getchar();
    return 0;
}

output : e_magic : 5a4d string buffer : 00B53A50

e_magic correct.


text:
Q: Given real number $x_1, x_2, \ldots, x_n$ such that $x_1 + x_2 + \ldots +x_n>0$, must this other inequality be true? Given real numbers $x_1, x_2, \ldots, x_n$ such that
$$x_1 + x_2 + \ldots + x_n >0$$
with the condition that $\max\{|x_i|\}_{i=1}^n = \max\{x_i\}_{i=1}^n$, must it be true that
$${x_1}^m + {x_2}^m + \ldots + {x_n}^m > 0$$
for all natural numbers $m$? If so, can you prove it?
I don't know how to approach the problem. Is there any generalization of the power-mean inequality to real numbers that might help? The inequality clearly holds true for all even $m$ from the Trivial Inequality, but the case for odd $m$ feels difficult.
Thanks, I appreciate any help!


text:
Q: b such that Ax = b has no solution having found column space $A:=\begin{bmatrix}
  2 & 6 & 0 \\
  3 & 1 & 3 \\
  1 & 0 & 0 \\
  4 & 8 & 1
 \end{bmatrix}$
I've found the basis for the column space by doing row reduction (i.e. basis is just the columns vectors of A in this case), and the null space only has the trivial solution.
Question
Find a basis for $B = \{b \in R^4 \ | \ Ax = b \ has \ no\  solution\}$.
Is there a quick way of doing this? I know I can augment A with $b = (b_1, b_2, b_3, b_4)^T$, do row reduction, and then look at the row of zeros, but that seems quite laborious?

A: When you multiply a matrix by a (column) vector, you get a vector that is a linear combination of the columns of the matrix, where the coefficients/weights come from the components of the column vector. I'm too lazy to illustrate with a $4\times 3$ example, so here's a $2\times 2$ example: $$Ax=\begin{pmatrix} \mathbf{A_1} & \mathbf{A_2}\end{pmatrix}\begin{pmatrix}x_1 \\ x_2\end{pmatrix}=x_1\mathbf{A_1}+x_2\mathbf{A_2}$$
where $\mathbf{A_1}$ is the first column of the matrix $A$ and $\mathbf{A_2}$ is the second column.
In other words, $Ax$ is a linear combination of the columns of $A$. But the column space of $A$, i.e. the image of $A$, is just the span of the columns of $A$. So the equation $Ax=b$, which says that $b$ is a linear combination of the columns of $A$, will have a solution if and only if $b$ is in the column space of $A$.

A: Denote $A\in\mathbb{F}^{m\times n}$ by
$$
A=\begin{bmatrix}a_{11} & a_{12} & . & . & . &  &  & a_{1n}\\
a_{21} &  &  &  &  &  &  & a_{2n}\\
. &  & . &  &  &  &  & .\\
. &  &  & . &  &  &  & .\\
. &  &  &  & . &  &  & .\\
\\
\\
a_{m1} & a_{m2} & . & . & . &  &  & a_{mn}
\end{bmatrix}
$$
and
$$
x=\begin{bmatrix}x_{1}\\
x_{2}\\
.\\
.\\
.\\
\\
\\
x_{n}
\end{bmatrix}
$$
then
$$
Ax=\begin{bmatrix}a_{11}x_{1}+a_{12}x_{2}+...+a_{1n}x_{n}\\
a_{21}x_{1}+a_{22}x_{2}+...+a_{2n}x_{n}\\
.\\
.\\
.\\
\\
\\
a_{m1}x_{1}+a_{m2}x_{2}+...+a_{mn}x_{n}
\end{bmatrix}=\begin{bmatrix}a_{11}\\
a_{21}\\
.\\
.\\
.\\
\\
\\
a_{m1}
\end{bmatrix}x_{1}+\begin{bmatrix}a_{12}\\
a_{22}\\
.\\
.\\
.\\
\\
\\
a_{m2}
\end{bmatrix}x_{2}+...+\begin{bmatrix}a_{1n}\\
a_{2n}\\
.\\
.\\
.\\
\\
\\
a_{mn}
\end{bmatrix}x_{n}
$$
Note that column matrices that are multiplied by the $x_{i}$ are
the columns of $A$ hence any vector $b$ of the form $b=Ax$ is a
linear combination of the columns of $A$ and thus in the span of
the columns of $A$.
On the other hand, denote the columns of $A$ as $C_{1},C_{2},...,C_{n}$.
If $b$ is a linear combination of the columns of $A$ this precisely
means that there are scalars $\alpha_{1},\alpha_{2},...\alpha_{n}$
s.t
$$
b=\alpha_{1}C_{1}+\alpha_{2}C_{2}+...+\alpha_{n}C_{n}
$$
and we see (using the above about $Ax$) that choosing $x_{i}=\alpha_{i}$
would give us $Ax=b$.
We conclude that the span of the columns of $A$ is precisely the
set of solutions $Ax=b$, thus you are looking for all the vectors
in the space that are not in that spanned subspace
Note: Since $0\not\in B$ (since $Ax=0$ have a solution, $x=0$)
then $B$ is not a subspace and thefore we can't talk about a basis
for this space.


text:
Q: Selecting css components during yeoman initialization, twitter bootstrap and angular I am trying to use angular, yeoman, and sass at the same time, also I only wanted some css components in twitter bootstrap, so I tried scaffolding my app like this
yo angular --coffee

And answered yes for the following questions,

would you like to install twitter bootstrap & would you like to use compass sass blah2x.

I answered yes,
Now the application is ready to go, but I have few concerns.

*

*it loads all twitter bootstrap components, I actually wanted only the normalize.scss

How do I selectively use an scss component, because it builds all files, making my codebase super big because of unnecessary imports.
Thank you.

A: It sounds like you may need  yeoman install yeoman-normalize.scss and then inside your main.scss file add a import line to correctly add normalize.scss
So:
@import "../components/yeoman-normalize.scss/yeoman-normalize";


text:
Q: 'react-native run-android' with USB tethering not installing app on device (note 4) I am trying to test my app through USB tethering (this app is currently working on Xcode and iOS Emulator). I have enabled tethering on 'Developer Options on my phone'
About Device
Samsung Note 4
Android 6.0.1
This is what i tried.
I ran this command
adb devices

react-native run-android

But the app is not installing on my Phone. Am i missing a step?

A: I've never done this with USB tethering. It seems like you need to do a bit more wiring to set up the app on your device outside of sharing internet connection. If you are open to an easy alternative you can try using Expo with create-react-native-app. If you have a simple app, you can run your code on your actual device by scanning a QR code.
The quickest way I've found to do test this out is with repl.it.


text:
Q: HQL: Subquery returns more than 1 row I'm new to HQL and I need help on this error.
QUERY:
 String hqlsearchSelect =
                "select new com.eteligent.core.loans.paging.LoansAppCustomerPageItem("
                    + "main.loanno, (SELECT acct.id.clientid FROM LMSAccountInfo acct WHERE acct.loanno = main.loanno), (SELECT acct.name FROM LMSAccountInfo acct WHERE acct.loanno = main.loanno), main.acctsts, "
                    + "main.loanbal, (SELECT acct.matdt FROM LMSAccountInfo acct WHERE acct.loanno = main.loanno) )";

I think the query can't identify which record is it going to return.
CONSTRUCTOR(LoansAppCustomerPageItem):
public LoansAppCustomerPageItem( final String acctNo, final String cifNo, final String customerName, final Integer acctStat, final BigDecimal acctBal, final Date acctDueDate )
{
    super();
    this.acctNo = acctNo;
    this.cifNo = cifNo;
    this.customerName = customerName;
    this.acctStat = acctStat;
    this.acctBal = acctBal;
    this.acctDueDate = acctDueDate;
}

A: If you wanna just one row from subquery use LIMIT 1 at the end of subquery.


text:
Q: Can I find the remainder more efficiently? Here :
https://github.com/gnufinder/prime-factor
I submitted a contribution with the goal to find a prime factor of the number
2222+3333.
The number has 3,638,334,640,025 digits, so ECM will take too long, but pollard-rho might be feasible, if there is a computer which can handle such numbers.
With normal hardware, only trial division will work. A primility test for such a number will be virtually hopeless.
You can see programs for GAP and PARI/GP determining the remainder if the number is divided by p, but I think this can be improved.
Does anyone have an idea how I can improve my programs?

A: You can calculate a^b modulo p in O(ln b). So if you refrain from turning your number into a binary or decimal number, you can check divisibility by a few hundred million small primes quite quickly.
Other calculations may be possible without evaluating the number.

A: If you want to crowd source anything, it's best to make it as easy as possible to contribute. Having to install a rather unusual language environment, like GAP or PARI/GP, is a boundary that would prevent most people from contributing.
What you can do to make it as easy as possible to contribute is to write a server and an API which can generate a search range and collect results, and a JavaScript version so that potential contributors can just visit a page and leave that page running in background. The web page should automatically picks a range, compute the range, and submits the result to the server. Doing this in a Github issue page is too cumbersome, you would have difficulties collecting the result as well.
Having an API also makes it possible for more serious contributor to contribute an implementation in different languages. Once you have a few different popular languages (e.g. C, Java, Python, Mathematica), it increases the likelihood that most people will have one of the environments already installed.
Having multiple implementations also allow each implementations to cross check each other. Like most crowd sourced computation project, you need to care about security. It's possible to submit false data, so you want to assign the same ranges multiple times to different people to have a degree of confidence that any false data are going to be voted out by the majority.


text:
Q: Creating an event handler for user right clicking and inspecting an element in Firefox or Chrome This is probably a question motivated more by concern for privacy than the potential for applicability, but is there a way to create an event handler that picks up the event of the user right clicking and selecting "inspect element" in Chrome or Firefox?
If there's not clear answer for this, is there a way to handle events for right click menu selections?

A: a fiddle I put together, you can get all the information on the element that the mousedown
event was on
document.addEventListener('contextmenu', function(e) {
    e.preventDefault();
}, false);

document.addEventListener("mousedown", function(e) {
    console.log(e); // you can inspect the click event

    $this = $('.cmenu');

    if (e.which === 3){ // right click = 3, left click = 1
        $this.addClass('open');
        $this.css({
            'left': e.pageX - $this.width() / 2,
            'top': e.pageY - $this.height()
        });
    }else if(e.which === 1 && e.target.nodeName == "HTML"){
        $this.removeClass('open');
    }
});

http://jsfiddle.net/MKBdv/1/

A: You can listen to event click, add check whether it is right click:
document.addEventListener("mousedown", function(e) {
    console.log(e); // you can inspect the click event

    if (e.which === 3) { // right click = 3, left click = 1
        alert("right click");
    }
});

// prevent context menu show up
document.addEventListener('contextmenu', function(e) {
    e.preventDefault();
}, false);


text:
Q: Recursion ceiling and radicals of integers Given $n,k\in\mathbb Z$ what is the minimum $r$ needed such that following iteration is $\leq2$?
$$n_0=n$$
$$n_1=\lceil n_0^{1/k}\rceil$$
$$\vdots$$
$$n_{i+1}=\lceil n_i^{1/k}\rceil$$
$$\vdots$$
$$n_r\leq2$$

What is the gap $r-\frac{\log_2\log_2 n}{\log_2k}$?

A: If $n_0\le 2$ then $r=0$, so we assume that $n_0\ge 3$.
If $k\le 0$ then $n_1\le 2$ and $r=1$, so we assume that $k\ge 1$.
If $k=1$, then $n_1=n_0$ and $n_i$ newer is not bigger than $2$, so we assume that $k\ge 1$.
By an  induction with respect to $j$ we can check that $n_r\le 2$ iff $n_{r-j}\le 2^{k^j}$ for each $j$. Thus $2^{k^{r-1}}<n_0\le 2^{k^r}$ that is $r=\lceil \log_k \log_2 n\rceil$ and the gap is less than $1$.


text:
Q: Play Framwork Java Angular - redirect to html page I have a ToDoController.java and the method
public static Result getAllToDos() {

     return ok(index.render("Your new application is also ready."));
    }

How can i redirect the page to ToDo.html using Play framework.
I am trying to write an application using Angular/Java/Play
My route file
GET     /                           controllers.Application.index()

GET     /            controllers.Assets.at(path="/public",file="index.html")

GET     /todo                          controllers.ToDoController.getAllToDos()

A: Try with this
public static Result getAllToDos() {
  return redirect("/ToDo.html");
}


text:
Q: Including filtering-criteria in Tweepy Streaming API I would like to collect all tweets that contain on the following words:
Bitcoin, Ethereum, Litecoin or Denarius
However, I want to exclude tweets than can be classified as retweets and tweets that contain links. I know from the following website (https://www.followthehashtag.com/help/hidden-twitter-search-operators-extra-power-followthehashtag) that I can add -filter:links to exclude tweets that contain links. This is clearly visible by comparing the following search term;
https://twitter.com/search?f=tweets&vertical=news&q=Bitcoin&src=typd

with https://twitter.com/search?f=tweets&q=Bitcoin%20-filter%3Alinks&src=typd

The same applies for retweets, where I can use -filter:retweets (see https://twitter.com/search?f=tweets&q=Bitcoin%20-filter%3Aretweets&src=typd)
I want to add these criteria to make sure that I reduce the "noise" and be less likely to violate any API-limitations.
I wrote the following Python-script:
import sys
import time
import json
import pandas as pd
from tweepy import OAuthHandler
from tweepy import Stream
from tweepy.streaming import StreamListener

USER_KEY = ''
USER_SECRET = ''
ACCESS_TOKEN = ''
ACCESS_SECRET = ''

crypto_tickers = ['bitcoin', 'ethereum', 'litecoin', 'denarius', '-filter:links', '-filter:retweets']

class StdOutListener(StreamListener):

def on_data(self, data):
    tweet = json.loads(data)
    print(tweet)

def on_error(self, status):
    if status == 420:
        sys.stderr.write('Enhance Your Calm; The App Is Being Rate Limited For Making Too Many Requests')
        return True
    else:
        sys.stderr.write('Error {}n'.format(status))
        return True

if __name__ == "__main__":
listener =  StdOutListener()
auth = OAuthHandler(USER_KEY, USER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_SECRET)

stream = Stream(auth, listener)
stream.filter(languages=['en'], track=crypto_tickers)

However, the output clearly shows tweets that are retweets and contain links.
Q1: How can I correctly include the search criteria  in my script and get the correct output?
Q2: According to the official documentation the Streaming API allows up to 400 track keywords (https://developer.twitter.com/en/docs/tweets/filter-realtime/overview/statuses-filter.html). Do my two filter criteria classify as 2 track keywords?
Thanks in advance,

A: A1. You cannot use the -filter: syntax on the Streaming API. The full list of available options is here in the documentation. The syntax you are trying to use is specific to the REST search API, not the standard realtime filter API (note that, in the enterprise realtime PowerTrack API, you can achieve what you are asking about, but this a commercial API).
A2. You have 6 track keywords in your code, including the -filter: elements, but those will never match.


text:
Q: how to configure AOLServer to use a different port than Apache2's 80 I am using a Ubuntu virtual machine.Where I installed OpenACS which depends upon AOLServer.To do so I had first shutdown Apache on this machine and then as per instructions given here
http://openacs.org/xowiki/ubuntu
Step 1)
 aptitude install postgresql
Step 2)
 aptitude install openacs
I had to shutdown Apache to do above installation.
Now the installation finishes.So I can access http://localhost:8000
but when ever I try to start Apache on this machine which was shutdown during installation I see the error
 service apache2 start
  * Starting web server apache2 (98)Address already in use: make_sock: could not bind to address 0.0.0.0:80  no listening sockets available, shutting down
Unable to open logs

So I thought may be OpenACS installs AOLServer so Aolserver might be listening on port 80 I check
 /etc/aolserver4/conf.d/openacs.sh

and here
AOL_USER=www-data
AOL_GROUP=www-data
AOL_ADDRESS=192.168.1.15
AOL_PORT=8000
RUN_DAEMON=yes

So AOLServer is not listening on port 80 upto here it is confirmed.
  netstat -tualp  | grep 80
tcp  0      0 somemachine.somedimain.:8000 *:*   LISTEN   21321/aolserver4-ns

so netstat shows only 8000 in  use.
Then why am I unable to start Apache in this case?
Edit
as ooshro below pointed out
to check
netstat -tualp | grep \:www the output
I got was
tcp        0      0 localhost:www           *:*                     LISTEN      2883/aolserver4-nsd

A: To check:
netstat -tualpn | grep 80

or
netstat -tualp  | grep \:www

without 'n' options, 80 resolve to www.
Edit "/etc/aolserver4/aolserver4.tcl":
array set debian_config {
HOSTNAME localhost
ADDRESS 127.0.0.1
HTTP_PORT 8080
HTTPS_PORT 443
}

Then restart aolserver4 and apache2
/etc/init.d/aolserver4 restart
/etc/init.d/apache2 restart

A: Ok Finally I resoved this problem.The default openacs install listens on port 8000, to avoid conflict with the default aolserver listening on port 80.
I had  to  put RUN_DAEMON=no in /etc/default/aolserver4 file although all the lines of this file were commented out but I still needed to add
RUN_DAEMON=no

That is what worked for me.


text:
Q: javascript - function.prototype.XXX , can I understand it as OOP Class static property/member XXX?     var seven;
    var new_seven;
    var new_seven_1;
    seven = function () {
          this.a = 7;
          };
    new_seven = new seven();
    new_seven_1=new seven();
    console.log(seven.prototype.a + "\t" + new_seven.a + "\t" + new_seven_1.a);
    seven.prototype.a = 49;
    console.log(seven.prototype.a + "\t" + new_seven.a + "\t" + new_seven_1.a);
    new_seven.a = 14;
    console.log(seven.prototype.a + "\t" + new_seven.a + "\t" + new_seven_1.a);
    new_seven_1.a=71;
    console.log(seven.prototype.a + "\t" + new_seven.a + "\t" + new_seven_1.a);

I have test the above script on Chrome, it output:
 undefined  7   7
 49 7   7
 49 14  7
 49 14  71

I am a newbie to javascript, and like to understand what is happening
Can I understand the above code as this:
seven.prototype.??? <== access to Class static properties
new_seven.??? / new_seven_1.???  // <== access to Class instance(Object) properties

I have view the MDN but I cannot found my question answered.
Thanks a lot!

A: You've more or less got it. You can think of prototype as attaching properties to the template for the object instead of to the instance.
Object.prototype is mostly used to attach member methods to the JavaScript equivalent of a class.
You could define member functions in the "constructor" of the class, the same way you define member properties, but that has a performance drawback since each object instantiated from the class would get its own copy of the method definition. By instead attaching the methods to the prototype, the object instances don't need to carry around those duplicate method definitions, so the objects consume less memory.
var seven = function () { // in OOP terms, think of this as a constructor
    this.a = 7; // the "a" property of the object is set equal to 7 when a new object is created
};
var new_seven = new seven(); // this runs the constructor, so "a" = 7
seven.prototype.a = 49;// this attaches an "a" property on the prototype or shared template
                       // for the seven object, but since seven's constructor overrides
                       // the "a" value, this won't actually do anything.
new_seven.a = 14; // this sets the instance's value to 14

A: seven.prototype.??? //adds another property to the function object. So that when you create another object say new_seven for instance, you are turning new_seven into an object and then with the use of new keyword in conjunction with the function seven(), new_seven inherits or gets it's own copy of the function seven()'s properties plus all the prototype variables.
say for instance in this block of code.
//constructor for car object
var car = function(){
    this.brand = "";
}
//But then you wanted it to have more properties so you use .prototype
car.prototype.price = "$100";
//you are adding another property for the constructor car() which is price
//with the default value of $100

//then you decide to create a new car
var somecar = new car(); //somecar inherits a brand new properties of car()
somecar.brand = "Porsche";// you decide what brand somecar is without affecting the properties of the constructor car()
somecar.price = "$100,000"; //with the help of prototype, the constructor car() had a new property which is price and can now be inherited by new objects.
//you then change the default price from which is $100 to $100,1000, but this doesn't affect the car() constructor which is neat.

//You may now access the somecar's properties note: that these properties can be dynamically changed.
console.log("brand : "+somecar.brand+" , price :"+somecar.price);

hope this helps.


text:
Q: ReactJS In-Line Function Running Before Component Mounts I have a div that should be hidden unless a certain <option> is selected in a <select> element
<div id='mailingAddrElms' className='col-md-5 col-sm-6' style={{display: this.showOrHideStateProvince()}}>

showOrHideStateProvince() {
    console.log('showing or hiding state/province options!');
    let mailingAddrElms = document.getElementById('mailingAddrElms');
    let prevAddrElms = document.getElementById('prevAddrElms');
    console.log(mailingAddrElms);
    console.log(prevAddrElms);
}

componentDidMount() {
    console.log('MOUNTED');
}

The showOrHideStateProvince() method is being ran before the component mounts as can be seen from this console output.

showing or hiding state/province options!
AddressForm.js:181 null
AddressForm.js:182 null
AddressForm.js:186 MOUNTED

It is very important that I wait for the component to mount before trying to retrieve elements by ID because then my magic controls won't be magical...
Any help is much appreciated, this is my first professional proj using React and I had no time to get ramped up..
I hope I shared enough snippets to paint the picture of my issue, but I really cannot be showing much more...

A: Did you try calling the showOrHideStateProvince method within componentDidMount?

A: Per @FranreySaycon comment, replacing the in-line function call on the div element with a ternary operator based on component state solves this issue painlessly. I just have a separate function now to record state then the ternary operator returns styles to the div.


text:
Q: WP_query issue with no posts I am using form for my archive page so user can specify which posts they want to see and how they want to see them. I have it setup so they can choose ascending or descending order, posts per page etc, using $_GET in my forms. However I have also set up form to set display posts by year/month:
<select name="monthnum">

          <option value="null">Month</option>

          <option value="1">January</option>

          <option value="2">February</option>

          <option value="3">March</option>

etc. for all month and the same one for year
then my query arguments look like this:
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;

    $custom_args = array(

        'post_type' => 'post',
        'posts_per_page' => $_GET["posts-per-page"],
        'paged' => $paged,
        'order' => $_GET["order"],
        "orderby" => "date",
        "year" => $_GET["year"],
        "monthnum" => $_GET["monthnum"]

      );

    $custom_query = new WP_Query( $custom_args );

So far I added a couple of posts to test things so they are all august 2015 and if i set these through $_GET, it displays well however if I try to do January or any other month apart from August, my archive page gets redirected to the page with the loop which is index.php in my case and it display "no posts..." while it should stay on the same page and  display "No posts..." on it. as I've set it up. There's no need to post rest of the code since I've figured out that the redirection happens immediately after new WP_query is created. What might cause this issue? Again $_GET ["posts per page"] and $_GET["order"] all work as expected.

A: By using those named GET variables such as year or monthnum you effectively short circuit the URL rewrite (if you are using pretty permalinks). This way you end up querying the main WP_Query instance first and effectively making yours completely useless (well, you do alter the posts_per_page attribute so there's that). Anyway, the point is that there is a base class WP that issues a 404 when the main WP_Query instance doesn't return posts (which is the case) and the 404 template is invoked (if your theme has it) or if it's missing the index template is used (which seems to be confirmed by your question).
Now, the quickest fix is to basically rename your GET variables into q_year or q_monthnum for example.


text:
Q: How can i add TrimString Middleware in laravel 5.3? Just came to know that Laravel 5.4 has an awesome feature TrimString, which removes the white spaces from any input. I want this middleware in my 5.3 project, any idea how to do that?
I just copied the middleware from GitHub repo of Laravel but it is not working.
Thanks

A: If you want to use this feature in Laravel 5.3.
Add these two classes into your App\Http\Middleware
https://github.com/laravel/framework/blob/5.4/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php
https://github.com/laravel/laravel/blob/master/app/Http/Middleware/TrimStrings.php
Updating it's namespace to App\Http\middleware.
Like:
TransformsRequest.php
namespace App\Http\Middleware;

use Closure;
use Symfony\Component\HttpFoundation\ParameterBag;

class TransformsRequest
{
    /**
     * The additional attributes passed to the middleware.
     *
     * @var array
     */
    protected $attributes = [];

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next, ...$attributes)
    {
        $this->attributes = $attributes;

        $this->clean($request);

        return $next($request);
    }

    /**
     * Clean the request's data.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return void
     */
    protected function clean($request)
    {
        $this->cleanParameterBag($request->query);

        $this->cleanParameterBag($request->request);

        if ($request->isJson()) {
            $this->cleanParameterBag($request->json());
        }
    }

    /**
     * Clean the data in the parameter bag.
     *
     * @param  \Symfony\Component\HttpFoundation\ParameterBag  $bag
     * @return void
     */
    protected function cleanParameterBag(ParameterBag $bag)
    {
        $bag->replace($this->cleanArray($bag->all()));
    }

    /**
     * Clean the data in the given array.
     *
     * @param  array  $data
     * @return array
     */
    protected function cleanArray(array $data)
    {
        return collect($data)->map(function ($value, $key) {
            return $this->cleanValue($key, $value);
        })->all();
    }

    /**
     * Clean the given value.
     *
     * @param  string  $key
     * @param  mixed  $value
     * @return mixed
     */
    protected function cleanValue($key, $value)
    {
        if (is_array($value)) {
            return $this->cleanArray($value);
        }

        return $this->transform($key, $value);
    }

    /**
     * Transform the given value.
     *
     * @param  string  $key
     * @param  mixed  $value
     * @return mixed
     */
    protected function transform($key, $value)
    {
        return $value;
    }
}

TrimStrings.php
namespace App\Http\Middleware;

class TrimStrings extends TransformsRequest
{
    /**
     * The attributes that should not be trimmed.
     *
     * @var array
     */
    protected $except = [
        //
    ];

    /**
     * Transform the given value.
     *
     * @param  string  $key
     * @param  mixed  $value
     * @return mixed
     */
    protected function transform($key, $value)
    {
        if (in_array($key, $this->except)) {
            return $value;
        }

        return is_string($value) ? trim($value) : $value;
    }
}

And add into your App\Http\Kernel.php
protected $middleware = [
    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    \App\Http\Middleware\TransformsRequest::class,
    \App\Http\Middleware\TrimStrings::class,
];

To use it just use:
dd(request('email'));

More on it:
https://laravel-news.com/laravel-5-4-middleware


text:
Q: Can you feed a macro to another macro as an argument, without the initial macro being expanded? Background: My code, which I cannot post here will eventually run on a microcontroller, and the macros just offer a way to create multiple pin definition functions, via 1 single macro define mechanic. I use windows and gcc to experiment around with those.
I tried to abstract the problem as much as possible. I use the std console functions cause it is convenient for me to display it in the console window. As such, I also save the file as .cpp and compile it with g++ on windows.
Say I set up my code like this:
#define MACRO2(_x)  foo##_x(_x)
#define MACRO1(_x)  MACRO2(_x)
#define BAR         3

void fooBAR(int num)
{
    std::cout << num << std::endl;
}

If I run the following code (working example)
int main()
{
    MACRO2(BAR);
    return 0;
}

first BAR gets inserted into ##_x and thus defines the function name which is to be called and then BAR gets inserted as the argument of that function and gets expanded to its value, so we get fooBAR(3). The code works, there are no errors.
Now if I try to add a macro in between (and this is the real world situation I am faced with for reasons I cannot go into), my code looks like this:
int main()
{
    MACRO1(BAR);
    return 0;
}

But this code throws an error, because when MACRO1(BAR) gets substituted with MACRO2(BAR), (BAR) then gets expanded into 3, and MACRO2(3) leads to foo3(3) which isn't defined, as confirmed by the error log:

error: 'foo3' was not declared in this scope

So the requirements are:

*

*I need to pass BAR into MACRO1 and it needs to be passed to MACRO2 without being expanded

*The word BAR has to stay exactly as it is, I know I could use ## in order to prevent it from expanding, but then I would need to add a char to BAR and the function call wouldn't work anymore.

Is it possible to somehow get this done? Pass a macro to another macro as an argument, without the initial macro being expanded in the process?

A:
But this code throws an error, because when MACRO1(BAR) gets
  substituted with MACRO2(BAR), (BAR) then gets expanded into 3, and
  MACRO2(3) leads to foo3(3)

Yes.  This is the specified preprocessor behavior for your particular set of macros.
After they are identified, the arguments to a function-like macro are fully macro-expanded before being substituted into the macro's replacement text, except where they are operands of the ## or # preprocessor operator.  Any appearances of those operators are evaluated, and then the resulting text is rescanned, along with any following text as appropriate, for additional macros to expand.

Is it possible to somehow get this done? Pass a macro to another macro as an argument, without the initial macro being expanded in the process?

Only where the argument is the operand of a ## or # operator.  The latter doesn't help you, but the former affords a workaround: you can pass an additional, empty argument so that you can perform a concatenation without changing the wanted argument:
#define MACRO2(_x)        foo##_x(_x)
#define MACRO1(_x,dummy)  MACRO2(_x##dummy)
#define BAR               3

int main()
{
    MACRO1(BAR,);
    return 0;
}

That expands to
int main()
{
    fooBAR(3);
    return 0;
}

If you want to avoid the extra comma, then you can do so by making MACRO1 variadic:
#define MACRO2(_x)      foo##_x(_x)
#define MACRO1(_x,...)  MACRO2(_x##__VA_ARGS__)
#define BAR             3

int main()
{
    MACRO1(BAR);
    return 0;
}

That expands to the same thing as the other.
Do note that both of these approaches afford the possibility of an error being introduced by providing unwanted extra argument values to the top-level macro.  One would probably suppose that most such errors would be caught at compile time, as the expansion would result in broken code, like the attempt in the question.  But it is hard to rule out the possibility that such an error would coincidentally expand to something that happened to be valid, but wrong.

A: One way to accomplish this is to change slightly the definition of BAR.
#define MACRO2(_x)  foo##_x(_x())
#define MACRO1(_x)  MACRO2(_x)
#define BAR()       3


text:
Q: Rails requires RubyGems >= 0.9.4. Please install RubyGems Having the same problems as this post, except I don't think the solution is the same unfortunately.
I'm getting this error message:
Rails requires RubyGems >= 0.9.4. Please install RubyGems

when I run a script/runner job in Cron, but it works perfectly fine when I run it in a terminal on the same server.
The rails server also runs fine. I only have trouble running script/runner's in cron. It seems to want to have a terminal attached...

A: Try which ruby and which gem from your cron job and also from the terminal. Are you accessing different binaries? You didn't mention which OS and which shell, but you may have a different $PATH when running headless.

A: The selected answer is completely correct, but something I'd suggest is to NOT use script/runner. The resources required to load the entire stack of your rails application is pretty intense for something to run regularly.
In my past experience, any cron jobs generally only have to deal with data (as opposed to say, generate static files, etc). In this case, you can very simply just load your models up, and since you've written your models the correct way (fat models), you can easily do your data processing with a few model methods.
Of course, all the above depends completely on your task, so take it with a grain of salt :)
I suppose this was a sort of answer to a problem that may not exist, and wasn't asked here, but just thought I'd throw my two cents in ;)

A: You wouldn't happen to be working on OSX? You should be installing a newer ruby rails and gems off macports instead. Google for the instructions...

A: As indicated by earlier posts, your Cron is using a different gem command source — also try which gem and gem -v. You may have a library set in your .bash_profile (or similar shell configuration or perhaps by other means, setting proper Ruby/Rails environment (i.e., Locomotive or other all-in-one environment).
To update your gem setup:
gem update --system
More information here - http://www.rubygems.org/read/book/1


text:
Q: Convert HMAC Hash from Python to PHP Im trying to convert a Python script to PHP and I have trouble getting the same hmac hash values (hmac_signature).
Python script:
import hashlib
import hmac
import json
#Pre shared secret key
secret = "cd01985/813hip914Vnn04&1#11ai761"
#The message I will send
message = {"user_id": "Frank", "query": "Dog"}
#Output message: {'user_id': 'Frank', 'query': 'Dog'}
#Encode the secret using UTF-8
secret_encoded = secret.encode('utf-8')
#Output secret_encoded: b'cd01985/813hip914Vnn04&1#11ai761'
#Dump dict to string and encode using UTF-8
message_encoded = json.dumps(message).encode('utf-8')
#Output messag_encoded: ab742454c0158c3ec8d8c9c8965381567d45bee77e6f8d9aacb2239587285f87
#Compute the HMAC hash and convert to string of hex chars
hmac = hmac.new(secret_encoded, message_encoded, hashlib.sha256)
#Output hmac: <hmac.HMAC object at 0x000001E05BE4BE50>
hmac_signature = hmac.hexdigest()
#Output hmac_signature: ab742454c0158c3ec8d8c9c8965381567d45bee77e6f8d9aacb2239587285f87

PHP:
<?php
    //Pre shared secret key
    $secret = "cd01985/813hip914Vnn04&1#11ai761";
    //The message I will send
    $message = array(
        'user_id'=>"Frank",
        'query'=>"Dog"
    );
    //Output $message: Array ( [user_id] => Frank [query] => Dog )
    //Encode the secret using UTF-8
    $secret_encoded = utf8_encode($secret);
    //Output $secret_encoded: cd01985/813hip914Vnn04&1#11ai761
    //Dump dict to string and encode using UTF-8
    $message_encoded = json_encode($message);
    //Output $message_encoded: {"user_id":"Frank","query":"Dog"}
    $message_encoded = utf8_encode($message_encoded);
    //Output $message_encoded: {"user_id":"Frank","query":"Dog"}
    //Compute the HMAC hash and convert to string of hex chars
    $hmac_signature = hash_hmac('sha256', $message_encoded, $secret_encoded, false);
    //Output $hmac_signature: e4fd77b03cd58b174c3f6f0ad52a484386280289127f5fa7251df1686c3fb582
?>

Do anyone know why im getting different hash?
Edit1: What is json.dumps(message) converted into PHP, json_encode($message) dont give me same output?

A: I tried your code and message_encoded in Python returns b'{"query": "Dog", "user_id": "Frank"}' for me.
The difference to PHP are the spaces which can be avoided in Python with
message_encoded = json.dumps(message, separators=(",", ":")).encode('utf-8')

Then the resulting hmac_signature is the same as in PHP.
Be aware that you have to use Python 3.7 or newer to ensure that the order of keys in the dict stays the same as given in the dict literal.


text:
Q: Pull-back of knots in branched covers and the Alexander polynomial Given a knot $K \subset S^3$ one can form its double branched cover $\Sigma_2(K)$ and consider the pull-back knot $\widetilde{K} \subset \Sigma_2(K)$ of $K$ to $\Sigma_2(K)$ (the locus fixed by the involution of $\Sigma_2(K)$). Here a few questions I would like to ask

*

*How do I compute the Alexander polynomial of $\widetilde{K}$?

*Can I compute $\Delta_{\widetilde{K}}(t)$ from $\Delta_K(t)$ plus some torsion invariants of $\Sigma_2(K)$?

*Is there a formula for $\Delta_{\widetilde{K}}(t)$ in the case when $\widetilde{K}$ comes from a torus knot $K \subset S^3$?

A: Corollary 4.2 from the paper "Metabelian representations, twisted Alexander polynomials, knot slicing, and mutation" by Herald, Kirk and Livingston gives the followwing recipe to compute Alexander polynomial of the lift of $K$ to the $n$-fold cover $\Sigma_n(K)$:
$$\Delta_{\widetilde{K}_n}(t) = \prod_{i=0}^{n-1} \Delta_{K}(\xi_n^i t^{1/n}),$$
where $\xi_n = \exp(\frac{2 \pi i}{n})$.


text:
Q: BoundingBox Matlab I have an image where I want to get region per region from the same using BoundingBox on MATLAB, this is the example where I use BoundingBox:
Ic=regionprops(logical(I3),'BoundingBox');

Where I3 is the image that I want to get region per region and then display region per region, the unique thing that I know about BoundingBox is that in my case, Ic is the variable where they saved the regions from the I3 Image that are 103 field or region, but I don't know how to display region per region in different figure, I understand that doing that, MATLAB will show 103 figures, I dont have any problem with that.

A: The result of finding the BoundingBox with regionprops is a rectangle defined by [x, y, width, height]. You can use these results to plot a rectangle using the built-in rectangle function.
If you wanted to put them all on the same axis you could do:
fig = figure;
him = imshow(I3);
hold on;

colors = hsv(numel(Ic));

% Now plot all the rectangles
for k = 1:numel(Ic)
    rectangle('Position', Ic(k).BoundingBox, 'EdgeColor', colors(k,:));
end

And if you want a new figure for every bounding box result:
% Anonymous function to help with the conversion from rect
rect2rng = @(pos,len)ceil(pos):(ceil(pos)+len-1);

for k = 1:numel(Ic)
    rect = Ic(k).BoundingBox;
    subImage = I3(rect2rng(rect(2), rect(4)), rect2rng(rect(1), rect(3)));
    fig = figure;
    him = imshow(subImage);
    title(sprintf('Bounding Box #%d', k));
end

A: The idea about plot all the rectangles is a great idea and, exactly, I want a new figure for every bounding box, but the code that you suggest, only display the same image 103 times, and not each figure per separated, the code that I used is:
Ic=regionprops(logical(I3),'BoundingBox');
fig = figure;
him = imshow(I3);
hold on; colors = hsv(numel(Ic));
for k = 1:numel(Ic)
  fig = figure;
  him = imshow(I3);
hold on;
rectangle('Position', Ic(k).BoundingBox);
end


text:
Q: Footnote on the wrong page (without floats involved) I've a \footnote that appears in the wrong page. I've read that this may happen when floats are involved or when there are multiple footnotes on a single page. But in my case there's only one footnote.
Below you can find my MWE. I've tried to reduce it as much as possible, and it was very hard to keep the problem appear: actually I find it very strange that even removing that \marginpar, the problem seems solved.
I guess that this could be due to how TeX tries to "fill" the pages, but I would expect that a footnote is kept on the page from where it is called, unless in special circumnstances. I know that my MWE may sound a lot "artificial", but it comes from a normal math thesis.
The use of \raggedbottom or \interfootnotelinepenalty (suggested here: Keep all footnotes on the according page) didn't help.
%!TeX encoding = utf8
%!TeX program = pdflatex

\documentclass[a4paper, 11pt]{book}

\usepackage{geometry}
\usepackage[eulerchapternumbers, palatino=false, parts=false]{classicthesis}
\usepackage[proportional, oldstyle]{cochineal}
\geometry{width=28pc, height=56pc}

\usepackage{lipsum}

\begin{document}

\pagestyle{empty}

\lipsum[1-3]

Lorem ipsum.\footnote{Footnote in the wrong page.}

\begin{equation}
\dots
\end{equation}

\vspace{13.5\baselineskip}\par
Lorem ipsum\par
Lorem ipsum\par
Lorem ipsum.

\goodbreak
\marginpar{Lorem ipsum}
\lipsum[1]

\end{document}

This is the (wrong) output I get:

EDIT:
For completeness, I add a less minimal and more natural working example,
without that \goodbreak:
\documentclass[a4paper, 11pt]{book}

\usepackage{geometry}
\usepackage{amsmath}
\usepackage[palatino=false]{classicthesis}
\usepackage[proportional, oldstyle]{cochineal}
\geometry{width=28pc, height=56pc}

\usepackage{lipsum}

\begin{document}
\pagestyle{empty}

\makeatletter
\newcounter{step}
\setcounter{step}{1}
\newcommand\step[1]{%
    \par\bigskip\noindent
    \textbf{Step \thestep.} \textit{#1}%
    \marginpar{#1}%
    \nobreak\par\nobreak\medskip
    \stepcounter{step}}
\makeatother

It is easy to prove by induction that for any $x\in I$ and for any positive integer $k\le r$ it holds:
\begin{equation}
\label{e:higher_derivatives_psi}
\frac{d^k\Psi(\phi)}{dx^k}=H_k\left(x,\,\phi'(f(x)),\,\phi''(f(x)),\dots,\, \phi^{(k)}(f(x))\right).
\end{equation}

Again by induction, it is evident that each $H_k$ is of the form
\begin{equation}
\label{e:hk_form}
H_k(x, y_1, \dots, y_k) = \sum_{i=1}^{k} h_{k,i}(x)y_i
\end{equation}
where $h_{k,i}$ are continuous functions of $x$ and $h_{k,k} = s^{-1}f'(x)^k$.

Now let $\phi$ be a generic solution of Schröder's equation, and let
\begin{equation}
\eta_1 = \phi'(0),\quad \eta_2 = \phi''(0), \quad \dots\quad \eta_r = \phi^{(r)}(0).
\end{equation}
From~\eqref{e:higher_derivatives_psi} we deduce that for $k=1,\dots,r$ we have
\begin{equation}
\label{e:etacondition}
\eta_k = H_k(0, \eta_1,\dots,\eta_k).
\end{equation}
This condition is trivial for $k=1$, since it follows directly from the definition of $H_1$, and it does not impose any condition on $\eta_1$. Conversely, if we fix $\eta_1 = \eta$, then each $\eta_k$ ($2\le k\le r$) is uniquely determined by the recurrent relation
\begin{equation}
\label{e:eta_recursive}
\underbrace{\left(1-\frac{f'(0)^k}{s}\right)}_{\displaystyle=1-s^{k-1}\ne0}\eta_k=\sum_{i=1}^{k-1} h_{k,i}(0)\eta_i
\end{equation}
as it follows directly from~\eqref{e:hk_form} and~\eqref{e:etacondition}.

\step{Assumptions and choice of constants}
\label{s:costants}

We assume without loss of generality that $0$ is the left endpoint of~$I$.\footnote{If $0$ is in the interior of $I$, one can consider the two intervals $I_1=I\cap(-\infty,0]$ and $I_2=I\cap[0,+\infty)$.}

For $i=1,\dots,r$ and for any nonnegative real $\tau$ such that $[0,\tau]\in I$, let
\begin{equation}
L_i(\tau) = \max_{x\in[0,\tau]}|h_{r,i}(x)|,
\end{equation}
where $h_{r,i}$ are the continuous functions defined in~\eqref{e:hk_form}. It follows from~\eqref{e:hk_form} that for any $x\in[0,\tau]$ and for $k\in1,\dots,r$,
\begin{equation}
\label{e:hk_lipschitz}
\left|H_k(x,y_1,\dots,y_k)-H_k(x,z_1,\dots,z_k)\right|\le\sum_{i=1}^{k} L_i(\tau)|y_i-z_i|.
\end{equation}
The above Lipschitz condition will be useful to prove that the operator $\Psi$ is a contraction.

Now let us choose a sufficiently small $\tau$ such that
\begin{equation}
\label{e:sigma}
\sum_{i=1}^r\,L_i(\tau)\frac{\tau^{r-i}}{(r-i)!} < 1.
\end{equation}
The existence of $\tau$ is guaranteed because the left-hand side of~\eqref{e:sigma} is continuous with respect to $\tau$ and equals $0$ when $\tau=0$.

From now on, we denote by $T$ the interval $[0,\tau]$.

\step{The complete metric space $\mathcal{F}$}

\lipsum[1]

\end{document}

with the resulting wrong output:

A: The marginnote package avoids the use of floats (this also shows how to remove classicthesis, which often causes trouble):
\documentclass{scrbook}

\usepackage[proportional, oldstyle]{cochineal}
\usepackage[width=28pc, height=56pc]{geometry}
\usepackage{amsmath}
\usepackage{marginnote}
\renewcommand*{\marginfont}{\itshape}
\deffootnote{0em}{1.6em}{\thefootnotemark\enskip}

\makeatletter
\newcounter{step}
\setcounter{step}{1}
\newcommand\step[1]{%
    \par\bigskip\noindent
    \textbf{Step \thestep.} \textit{#1}%
    \marginnote{#1}%
    \nobreak\par\nobreak\medskip
    \stepcounter{step}}
\makeatother

\usepackage{mwe}

\begin{document}

It is easy to prove by induction that for any $x\in I$ and for any positive integer $k\le r$ it holds:
\begin{equation}
\label{e:higher_derivatives_psi}
\frac{d^k\Psi(\phi)}{dx^k}=H_k\left(x,\,\phi'(f(x)),\,\phi''(f(x)),\dots,\, \phi^{(k)}(f(x))\right).
\end{equation}

Again by induction, it is evident that each $H_k$ is of the form
\begin{equation}
\label{e:hk_form}
H_k(x, y_1, \dots, y_k) = \sum_{i=1}^{k} h_{k,i}(x)y_i
\end{equation}
where $h_{k,i}$ are continuous functions of $x$ and $h_{k,k} = s^{-1}f'(x)^k$.

Now let $\phi$ be a generic solution of Schröder's equation, and let
\begin{equation}
\eta_1 = \phi'(0),\quad \eta_2 = \phi''(0), \quad \dots\quad \eta_r = \phi^{(r)}(0).
\end{equation}
From~\eqref{e:higher_derivatives_psi} we deduce that for $k=1,\dots,r$ we have
\begin{equation}
\label{e:etacondition}
\eta_k = H_k(0, \eta_1,\dots,\eta_k).
\end{equation}
This condition is trivial for $k=1$, since it follows directly from the definition of $H_1$, and it does not impose any condition on $\eta_1$. Conversely, if we fix $\eta_1 = \eta$, then each $\eta_k$ ($2\le k\le r$) is uniquely determined by the recurrent relation
\begin{equation}
\label{e:eta_recursive}
\underbrace{\left(1-\frac{f'(0)^k}{s}\right)}_{\displaystyle=1-s^{k-1}\ne0}\eta_k=\sum_{i=1}^{k-1} h_{k,i}(0)\eta_i
\end{equation}
as it follows directly from~\eqref{e:hk_form} and~\eqref{e:etacondition}.

\step{Assumptions and choice of constants}
\label{s:costants}

We assume without loss of generality that $0$ is the left endpoint of~$I$.\footnote{If $0$ is in the interior of $I$, one can consider the two intervals $I_1=I\cap(-\infty,0]$ and $I_2=I\cap[0,+\infty)$.}

For $i=1,\dots,r$ and for any nonnegative real $\tau$ such that $[0,\tau]\in I$, let
\begin{equation}
L_i(\tau) = \max_{x\in[0,\tau]}|h_{r,i}(x)|,
\end{equation}
where $h_{r,i}$ are the continuous functions defined in~\eqref{e:hk_form}. It follows from~\eqref{e:hk_form} that for any $x\in[0,\tau]$ and for $k\in1,\dots,r$,
\begin{equation}
\label{e:hk_lipschitz}
\left|H_k(x,y_1,\dots,y_k)-H_k(x,z_1,\dots,z_k)\right|\le\sum_{i=1}^{k} L_i(\tau)|y_i-z_i|.
\end{equation}
The above Lipschitz condition will be useful to prove that the operator $\Psi$ is a contraction.

Now let us choose a sufficiently small $\tau$ such that
\begin{equation}
\label{e:sigma}
\sum_{i=1}^r\,L_i(\tau)\frac{\tau^{r-i}}{(r-i)!} < 1.
\end{equation}
The existence of $\tau$ is guaranteed because the left-hand side of~\eqref{e:sigma} is continuous with respect to $\tau$ and equals $0$ when $\tau=0$.

From now on, we denote by $T$ the interval $[0,\tau]$.

\step{The complete metric space $\mathcal{F}$}

\lipsum[1]

\end{document}


text:
Q: I am trying to downgrade my HP envy 8 1414 from Windows 8 to Windows 7 and need the sata controller driver I have downloaded several drivers and extracted the files, but none seem to be working for me. I have seen a couple of posts about this, but I keep running into the wall. Any help would be appreciated.

A: Booted in to Bios and under Storage Options, changed it from SATA to AHCI, booted with Windows 7 64bit cd and deleted the partitions, formatted the drive and installed Windows 7.


text:
Q: Counting the number of trees on $[n]$ Let $T_{n}$ be the number of trees on $[n]$. Explain the identity below in terms of $T_{n}$ and prove it.
$2(n-1)n^{n-2}=\sum_{k=1}^{n-1}\binom{n}{k}k^{k-1}(n-k)^{n-k-1}.$
So far I've got that $T_{n}=n^{n-2}$ so it shows up in the LHS. For the sum it looks like $k^{k-1}$ is the number of labeled rooted trees on $k$ vertices and $(n-k)^{n-k-1}$ is the same thing on $n-k$ vertices and $\binom{n}{k}$ is picking which $k$ go in the first tree. Why would we multiply these two numbers and how does that equal the LHS? A hint would be very nice. Thanks.

A: HINT: Assume that $n\ge 2$, and let $T$ be a tree on $n$ vertices. There are $n-1$ ways to choose an edge $\{u,v\}$ of $T$ and two ways to paint the one of the vertices $u$ and $v$ red and the other blue, so there are $2(n-1)n^{n-2}$ trees on $n$ vertices with a distinguished edge whose ends are so painted.
Fix $k\in[n-1]$. There are $k\cdot k^{k-2}=k^{k-1}$ ways to pick a tree $T_1$ on $k$ vertices and choose a vertex $v_1$ to be painted red, and $(n-k)(n-k)^{n-k-2}=(n-k)^{n-k-1}$ ways to pick a tree $T_2$ on $n-k$ vertices and choose a vertex $v_2$ to be painted blue; adding an edge between $v_1$ and $v_2$ gives you a tree on $n$ decorated as in the first paragraph.


text:
Q: Copy files to new dir and append date I'm copying over some files (txt/log files) from C:\Application\Logs\Log.txt (and Log2.txt etc) to C:\Logs
Code:
If Not File.Exists("C:\Logs\Log.txt") Then
                My.Computer.FileSystem.CopyFile(
        "C:\Application\Logs\Log.txt",
        "C:\Logs\Log.txt")
            End If

If the button is pressed multiple times, this will fail as the logs already exist in C:\Logs. So, I would like to append date to the end of the log before it is placed in the folder. Is this possible?
Thanks

A: Given your requirement, I think it will be better to prevent the multiple clicks to make duplicate process than to append the date:
Dim isProcessed As Boolean = False
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    If isProcessed Then
        Return
    End If
    isProcessed = True

    If Not File.Exists("C:\Logs\Log.txt") Then
        My.Computer.FileSystem.CopyFile(
          "C:\Application\Logs\Log.txt",
          "C:\Logs\Log.txt")
    End If

    isProcessed = False
End Sub

Nevertheless, if you want to add the DateTime, you could do that by having DateTime.Now.ToString("yyyyMMdd_HHmmss_fff") appended as text in your log file name too:
Dim isProcessed As Boolean = False
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    If isProcessed Then
        Return
    End If
    isProcessed = True

    Dim filename As String = "C:\Logs\Log_" & DateTime.Now.ToString("yyyyMMdd_HHmmss_fff") & ".txt"
    My.Computer.FileSystem.CopyFile("C:\Application\Logs\Log.txt", filename)

    isProcessed = False
End Sub

The check If Exist is no longer needed, since the time is different now


text:
Q: new document dialog showing master page header images I have a SharePoint team site and I made some changes in master page as below:

*

*Moved top menu links and search box below page heading

*In place of top links I placed an image called image1 and in place of search box I placed another image called image2

*Replacing SharePoint logo with my own logo and increasing its size

I did all this using DIV/CSS. Now I am no designer, not even close. So I had to do a lot of trial and error before every thing looked ok except this one issue which now I am facing and i.e. when you click on "new document" link which opens a dialog box where you can upload document, that window is also showing those logos (which I mentioned in point 2 above)
How can I get rid of that? I was thinking that if somehow I can find out if the dialog is open then I can hide those images using CSS/Jquery?
Here's partial code to given you and understanding where I have wrote code. My divs are named "mydiv" and "mydiv2" while rest of the code is SharePoint's default:

    <asp:UpdatePanel
        ID="WebPartAdderUpdatePanel"
        UpdateMode="Conditional"
        ChildrenAsTriggers="false"
        runat="server">
      <ContentTemplate>
        <WebPartPages:WebPartAdder ID="WebPartAdder" runat="server" />
        </ContentTemplate>
      <Triggers>
        <asp:PostBackTrigger ControlID="WebPartAdder" />
     </Triggers>
    </asp:UpdatePanel>

</SharePoint:AjaxDelta>

A: Fixed by using CSS class ms-dialogHidden as mentioned here:
https://sharepoint.stackexchange.com/questions/200195/new-document-dialog-showing-master-page-header-images/200197#200197


text:
Q: How to use the two_line_list_item in android? I have a ListView and the following adapter:
ArrayAdapter<Item> adapter = new ArrayAdapter<Item>(this, android.R.layout.two_line_list_item, items);

where items has the following type: ArrayList<Item>
The class items looks like:
public class Item {

    String foo1;
    String foo2;

    public String getLine1() {
        return foo1;
    }
    public String getLine2() {
        return foo2;
    }
}

but this is not working. Is it not possible to implement is this simple way?

A:
Is it not possible to implement is this simple way?

No, because that is not how ArrayAdapter works. You are welcome to create your own subclass of ArrayAdapter, override getView(), and fill in android.R.id.text1 and android.R.id.text2 with getLine1() and getLine2().


text:
Q: Create action inside another controller I am attempting to create a new User inside a controller for my Request class, but have having some difficulty.  Below is my 'create' action inside my Requests controller.  I realize I can't just call User.new, but am unsure how to structure the correct POST action.
def create
  @request = Request.new(params[:request])
  @user = User.find_by_email(@request.email)
  if @user.present?
    @request.user_id = @user.id
    @request.save
  else
    user = User.new
    user.email = @request.email
    user.zip = @request.zip
    user.save
    @request.user_id = user.id
    @request.save
  end

  respond_to do |format|
    if @request.save
      UserMailer.request_confirmation(@request).deliver
      UserMailer.request_notification(@request).deliver
      format.html { redirect_to confirmation_url }
      format.json { render json: @request, status: :created, location: @request }
    else
      format.html { render action: "new" }
      format.json { render json: @request.errors, status: :unprocessable_entity }
    end
  end
end

A: I'm not sure what's your problem, but you don't have to call User create POST action (action from User controller) to create user.
User.create - 'create' is method from ActiveRecord::Base, not from UserController.
In one action (e.g. Request create action) you can create many ActiveRecord object, no matter what class they are.
There are various ways to create database entity in rails. They could be called from models, controllers and others.
@u = User.new
@u.save! # try to save object in DB, if something goes wrong, throws exception

@u = User.create! # creates empty user object in database, '!' causes that if something goes wrong, create throws exception

@u = User.create # it won't throw exception even if object is invalid

@u = User.new
@u.email = @request.email
if @u.save
   # ok, it's in DB
else
   # something goes wrong, e.g. rails validations
end


text:
Q: Bootstrap space between columns I have this form with some inputs:

I would like to make the space between the input and the + and = symbols to be smaller. This is my code:

                         <input id="num1" class="sum form-control input-sm" type="text"          name="num1" value=" {$unique_id}" readonly="readonly" />

                         +

                         <input id="num2" class="sum form-control input-sm" type="text" name="num2" value=" {$unique_id2}" readonly="readonly" />

                         =

                         <input id="captcha" class="captcha form-control input-sm" type="text" name="captcha" style="width:20%" maxlength="2" />

If i leave the input and label in the same col

A: There are a couple different ways to do this. Here is a simple, easy way to get it done as well as maintain responsive qualities:
http://jsfiddle.net/hHWeG/
.form-group span {
    margin-left: 0.75em;
}

<form class="form-inline" role="form">

    <input id="num1" class="sum col-xs-10 input-sm" type="text" name="num1" value=" {$unique_id}" readonly="readonly" /> +

    <input id="num2" class="sum col-xs-10 input-sm" type="text" name="num2" value=" {$unique_id2}" readonly="readonly" /> =

      <input id="input" class="col-xs-10 input-sm" type="text" name="" />

</form>

A: The labels are inside divs with the col-lg-1 class so they'll always be a full column's width. Consider moving them into the same container as the inputs and styling from there.


text:
Q: unable to percolate : org.elasticsearch.index.percolator.PercolatorException: [myindex] failed to parse query [myDesignatedQueryName] I am following this guide and converting this percolate api java code in scala but when i run this  in SBT it throws following exceptions
[error] (run-main-0) org.elasticsearch.index.percolator.PercolatorException: [myindex] failed to parse query [myDesignatedQueryName]
org.elasticsearch.index.percolator.PercolatorException: [myindex] failed to parse query [myDesignatedQueryName]
    at org.elasticsearch.index.percolator.PercolatorQueriesRegistry.parsePercolatorDocument(PercolatorQueriesRegistry.java:194)
    at org.elasticsearch.index.percolator.PercolatorQueriesRegistry$RealTimePercolatorOperationListener.preIndex(PercolatorQueriesRegistry.java:309)
    at org.elasticsearch.index.indexing.ShardIndexingService.preIndex(ShardIndexingService.java:139)
    at org.elasticsearch.index.shard.service.InternalIndexShard.index(InternalIndexShard.java:420)
    at org.elasticsearch.action.index.TransportIndexAction.shardOperationOnPrimary(TransportIndexAction.java:193)
    at org.elasticsearch.action.support.replication.TransportShardReplicationOperationAction$AsyncShardOperationAction.performOnPrimary(TransportShardReplicationOperationAction.java:511)
    at org.elasticsearch.action.support.replication.TransportShardReplicationOperationAction$AsyncShardOperationAction$1.run(TransportShardReplicationOperationAction.java:419)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.elasticsearch.index.query.QueryParsingException: [myindex] Strict field resolution and no field mapping can be found for the field with name [content]
    at org.elasticsearch.index.query.QueryParseContext.failIfFieldMappingNotFound(QueryParseContext.java:393)
    at org.elasticsearch.index.query.QueryParseContext.smartFieldMappers(QueryParseContext.java:372)
    at org.elasticsearch.index.query.TermQueryParser.parse(TermQueryParser.java:95)
    at org.elasticsearch.index.query.QueryParseContext.parseInnerQuery(QueryParseContext.java:277)
    at org.elasticsearch.index.query.IndexQueryParserService.parseInnerQuery(IndexQueryParserService.java:321)
    at org.elasticsearch.index.percolator.PercolatorQueriesRegistry.parseQuery(PercolatorQueriesRegistry.java:207)
    at org.elasticsearch.index.percolator.PercolatorQueriesRegistry.parsePercolatorDocument(PercolatorQueriesRegistry.java:191)
    at org.elasticsearch.index.percolator.PercolatorQueriesRegistry$RealTimePercolatorOperationListener.preIndex(PercolatorQueriesRegistry.java:309)
    at org.elasticsearch.index.indexing.ShardIndexingService.preIndex(ShardIndexingService.java:139)
    at org.elasticsearch.index.shard.service.InternalIndexShard.index(InternalIndexShard.java:420)
    at org.elasticsearch.action.index.TransportIndexAction.shardOperationOnPrimary(TransportIndexAction.java:193)
    at org.elasticsearch.action.support.replication.TransportShardReplicationOperationAction$AsyncShardOperationAction.performOnPrimary(TransportShardReplicationOperationAction.java:511)
    at org.elasticsearch.action.support.replication.TransportShardReplicationOperationAction$AsyncShardOperationAction$1.run(TransportShardReplicationOperationAction.java:419)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)
[trace] Stack trace suppressed: run last compile:run for the full output.

here is my code
object PercolateApiES extends App{
  val node =nodeBuilder().client(true).node()
val client =node.client()

  val qb=QueryBuilders.termQuery("content","amazing")

val res=client.prepareIndex("myindex", ".percolator", "myDesignatedQueryName")
    .setSource(jsonBuilder()
        .startObject()
            .field("query", qb) // Register the query
        .endObject())
    .setRefresh(true) // Needed when the query shall be available immediately
    .execute().actionGet();
val docBuilder = XContentFactory.jsonBuilder().startObject();
docBuilder.field("doc").startObject(); //This is needed to designate the document
docBuilder.field("content", "This is amazing!");
docBuilder.endObject(); //End of the doc field
docBuilder.endObject(); //End of the JSON root object
//Percolate
val response = client.preparePercolate()
                        .setIndices("myindex")
                        .setDocumentType("myDocumentType")
                        .setSource(docBuilder).execute().actionGet();
node.close
}

When I write these commands using curl they work fine
curl -XPUT 'localhost:9200/myindex1' -d '{
  "mappings": {
    "mytype": {
      "properties": {
        "content": {
          "type": "string"
        }
      }
    }
  }
}'

{"acknowledged":true}

curl -XPUT 'localhost:9200/myindex1/.percolator/myDesignatedQueryName' -d '{
    "query" : {
        "term" : {
            "content" : "amazing"
        }
    }
}'

{"_index":"myindex1","_type":".percolator","_id":"myDesignatedQueryName","_version":1,"created":true}

curl -XGET 'localhost:9200/myindex1/content/_percolate' -d '{
    "doc" : {
        "content" : "This is amazing!"
    }
}'

{"took":231,"_shards":{"total":5,"successful":5,"failed":0},"total":1,"matches":[{"_index":"myindex1","_id":"myDesignatedQueryName"}]}

I am using elastic search-1.4.1 Please help me where i am making mistake and also i want to seethe results asi dont know how to do this in code
matches":[{"_index":"myindex1","_id":"myDesignatedQueryName"}

How can I fetch the result ,please help me and guide me ,Thanks

A: ES 1.4.0.Beta1 has introduced a breaking change which affects the percolator API. Basically, we need to set the index.query.parse.allow_unmapped_fields explicitly to true. Refer to http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/mapping-dynamic-mapping.html#_unmapped_fields_in_queries for details.
The actual conversation on adding this change is in their Github https://github.com/elasticsearch/elasticsearch/issues/6664.
Here is another related issue: index.query.parse.allow_unmapped_fields setting does not seem to allow unmapped fields in alias filters


text:
Q: How to prevent a mdichild form to move/repositioning on screen I want to fix the position of mdi child form. so that no one can move it from one location to another.
I try to implement the following code but it gives me error for screen.width
Here is my code:-
Place this code in a Module:
public Sub CenterMe(Myform as Form)
    with Myform
        Myform.Left = (Screen.Width - .Width) / 2
        Myform.Top = (Screen.Height - .Height) / 2 ' - mdiMain.StatusBar.Height
    End With
End Sub

now in the form load event of the children - call it like this:
Private Sub Form_Load()
    'do some initialization stuff...
    '...
    Call CenterMe(me)
End Sub

A: Once the initial location of the form is set, you can prevent form's position to be changed via overriding form's WndProc method and listen for WM_MOVE windows message like this.
protected override void WndProc(ref Message message)
{
    const int WM_SYSCOMMAND = 0x0112;
    const int SC_MOVE = 0xF010;

    switch (message.Msg)
    {
        case WM_SYSCOMMAND:
            int command = message.WParam.ToInt32() & 0xfff0;
            if (command == SC_MOVE)
                return;
            break;
    }

    base.WndProc(ref message);
}


text:
Q: Equivalent of Haskell's const function in Ramda Does Ramda have a function that works the same as Haskell's const function, i.e. takes two parameters and returns the first one?
I'm aware that it could be easily implemented as R.curry((a, b) => a), but if Ramda already has such a function, I think I should use it instead of my own implementation.

A: Ramda doesn't provide a function of type a -> b -> a. As Gothdo's answer states, Ramda does provide R.always :: a -> (() -> a) which is similar.
Adding an a -> b -> a function to Ramda was proposed in ramda/ramda#1680, but that thread has not been active for some time.
Sanctuary does provide a true const function, S.K :: a -> b -> a.

A: This function is named always in Ramda.

Returns a function that always returns the given value. Note that for non-primitives the value returned is a reference to the original value.
This function is known as const, constant, or K (for K combinator) in other languages and libraries.


text:
Q: Multiple monitor synchronization using java thread I am writing a tiny application (something a bit bigger than "HelloWorld"). The task is to create a single producer and several consumers. The producer generates integeres and puts them in a dynamic stack (which is my monitor object), and consumers try to get those integers from stack.
I do know how to create 1 producer + 1 consumer using a flag and a while with wait() inside. But how to do the same with multiple consumers.
Please have a look at my code:
public interface StackQueueIF {
    void push(int value);
    int pop();
}

public class DynamicStack implements StackQueueIF{

    private volatile int stck[];
    private volatile int tos;

    boolean valueSet = false;

    public DynamicStack(int size) {
        stck = new int[size];
        tos = -1;
    }

    @Override
    public synchronized void push(int item) {
        while(valueSet){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        if (tos == stck.length-1) {
            System.out.println("---------STACK HAS BEEN DOUBLED--------");
            int temp[] = new int[stck.length * 2];
            for (int i = 0; i < stck.length; i++)   temp[i] = stck[i];
            stck = temp;
            stck[++tos] = item;
        }else
            stck[++tos] = item;

        valueSet = true;
        notifyAll();
    }

    @Override
    public synchronized int pop() {
        while(!valueSet){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        valueSet = false;
        notifyAll();
        return stck[tos--];
    }
}

class Producer implements Runnable{
    StackQueueIF queue;
    String producerName;
    private static int counter = 0;

    public Producer(StackQueueIF queue, String name) {
        this.queue = queue;
        this.producerName = name;
        new Thread(this,producerName).start();
    }

    @Override
    public void run() {
        while(true){
            System.out.println(this.producerName + " puts " + (++counter)
              + " into stack");
            this.queue.push(counter);
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                System.err.println(producerName + " interrupted");
                e.printStackTrace();
            }
        }
    }
}

class Consumer implements Runnable{
    StackQueueIF queue;
    String consumerName;

    public Consumer(StackQueueIF queue, String consumerName) {
        this.queue = queue;
        this.consumerName = consumerName;
        new Thread(this, this.consumerName).start();
    }

    @Override
    public void run() {
        while(true){
            System.out.println(this.consumerName + " gets " + queue.pop() + " from stack");
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                System.err.println(consumerName + "interrupted");
                e.printStackTrace();
            }
        }
    }

}

public class QueueTester {
    public static void main(String[] args) {
        StackQueueIF queue = new DynamicStack(10);
        new Producer(queue,"Producer №1");

        new Consumer(queue,"Consumer №1");
        new Consumer(queue,"Consumer №2");
    }
}

A: This is how I would write the Stack
public interface IntStack {
    void push(int value);
    int pop() throws InterruptedException;
}

public class DynamicStack implements IntStack {
    private int size = 0, stack[];

    public DynamicStack() {
        this(16);
    }

    public DynamicStack(int capacity) {
        stack = new int[capacity];
    }

    @Override
    public synchronized void push(int item) {
        if (size + 1 == stack.length)
            stack = Arrays.copyOf(stack, stack.length * 2);
        stack[size++] = item;
        notifyAll(); // notify() would also do.
    }

    @Override
    public synchronized int pop() throws InterruptedException {
        while (size == 0)
            wait();
        return stack[--size];
    }
}


text:
Q: Linear Algebra: show that $F\cap (G+H) = G + (H\cap F)$ Let $E$ be a vector space, and $F, G, H$ subspaces of $E$ such that $G\subset F$.
The exercise is to show that:
$F\cap (G+H) = G + (H\cap F)$
I understand this identity as sets, but as spaces and subspaces I don't really know how to prove it with the formalism required, so I am looking for the way to work with this concepts of space and subspace.

A: When you use the operation $+$, I will assume you mean that $G+H = \{g +h \in E: g \in G, h \in H\}$.
Let $x \in F\cap(G+H)$. Since $F\cap(G+H) \subset G+H$, $x$ may be expressed as $x = g + h$  for some $g \in G$ and $h \in H$. However, since $F\cap(G+H) \subset F$, we have $x \in F$.
Observe that $h = x-g$. Clearly, $x-g \in H$. Now, since $G \subset F$, $g \in F$. Thus, since $ x \in F$ and $g \in F$, $x-g \in F \implies x-g \in H\cap F$. But observe that $x = g + (x-g) \implies x \in G + (H\cap F) \implies F \cap (G+H) \subset G+(H \cap F)$.
Now, let $y \in G + (H\cap F)$.  So, $y =g + r$ for some $g \in G$ and $r \in H\cap F$. We note that since $H \cap F \subset H$, $r \in H$. Thus, $y = g + r \in G+H$. However, since $H \cap F \subset F$, we also have $r \in F$. Again, since $g \in G$ and $G \subset F$, we have $g \in F$. Thus, since $F$ is a subspace and $r, g \in F$, $r + g \in F$. Thus, $y \in F$ and $y \in G+H$. It follows that $y \in F \cap (G+H) \implies G+(H \cap F) \subset F \cap (G+H)$. The result follows.

A: For the first inclusion, take $x \in F \cap (G+H) \Rightarrow x\in F \wedge x\in (G+H)$. Then exist $g \in G$ and $h \in H$ such that $x=g+h \in F$. As $G \subseteq F$ we have to $g \in F$ and how $F$ is a subspace $\Rightarrow$ $h \in F$. So $h \in H \cap F$ and $x=g+h \in G+(H\cap F)$.
For the second inclusion, take $x \in G+(H\cap F)$ so exits $g \in G \subseteq F$ and $y \in H \cap F$ such that $x=g+y$. As $y \in F$ and $F$ is subspace $\Rightarrow x \in F$.
 Also, $y \in H$ so $x=g+y \in G+H$, finally $x \in F \cap(G+H)$
$\textbf{Observation :}$ If you have $x+y \in F$ and $x \in F$ where $F$ is a subspace. Necessarily you have to $y \in F$ because $x+y=f \in F \Rightarrow y=f-x$ and how $F$ is a subspace : $y \in F$


text:
Q: SVN: shows edits on a file with authorships I've a question:
We are using SVN as way to manage our sources. Now, i would like to take a file and see who committed each part of the text.
Basically would be a big diff that takes all the version and as output shows the texts highlighting who committed which part.
For example:
A committed "Hi, today is Monday"
B committed the change "Hi, today is Thursday"
C committed the change "Hello, today is Thursday"
the output will be smt like "Hello[C],today is[A] Thursday[B]" (obviously not with brackets but coloring the edits with different colors per authors.
is it possible?

A: Have you heard of svn blame FILE ? It does exactly that. It looks better in a GUI client though.
EDIT: that's usually possible on a per line basis, unlike your example.