jquery datepicker & c#/aspnet - asynchronous database query

Question: I am working with the C#, ASP.NET framework [very new to this environment].  This is what I want to achieve:

Pass data from jQuery Datepicker textbox to controller
Parse the date, database query from the selected range
Asynchronously, send queried rows back to page to update content

Here is the HTML:
<form id="date" runat="server">
    <asp:Label AssociatedControlId="from_date" Text="From:" runat="server" />
    <asp:TextBox ID="from_date" Text="" runat="server" />
    <asp:Label AssociatedControlId="to_date" Text="To:" runat="server" />
    <asp:TextBox ID="to_date" Text="" runat="server" />
</form>

I have this snippet on the client side to handle the change event:
var dates = $('#from_date, #to_date').datepicker({
                if ( this.id == "to_date" )
                    $('#to_date').change();
            });

To call in the controller:
protected void to_date_UpdateHandler( object sender, EventArgs e ) {
  /* from here, I would query within the ranges in the "from_date"
     and "to_date" textboxes */
}

Obviously, this will cause a page refresh, but I want to pass the data along asynchronously.  How should I go about achieving this?  Thank you.
Answer: It's a little unclear from your question which particular jQuery 'datepicker' plugin you are using, so I will proceed to use the jQuery UI date picker for this example.
First off, there are some things you should be aware of when working with jQuery and ASP.NET WebFroms. Specifically, up until very recently, when server controls are rendered, their IDs get mangled by .NET. It is usually a good idea to stick to CSS classes when doing lots of client side scripting, but if you must use IDs, you can select controls like so:
var $toDate = $('input[id$=to_date]');

Secondly, you will need to communicate with the server via WebMethods or by configuring an ASPX page to return XML or JSON. ASP.NET MVC really makes this easy, but it's possible in WebForms and definitely worth your time (I despise UpdatePanels).
Now to some code.
ASPX:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>Example ASP.NET/jQuery Datepicker</title>
    <link type="text/css" rel="stylesheet" href="http://ajax.microsoft.com/ajax/jquery.ui/1.8.5/themes/redmond/jquery-ui.css" />

    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager" EnablePageMethods="true" runat="server">
    </asp:ScriptManager>
    <asp:Label ID="from_date_lbl" AssociatedControlID="from_date" Text="From:" runat="server" />
    <asp:TextBox ID="from_date" CssClass="from_date" Text="" runat="server" />
    <asp:Label ID="to_date_lbl" AssociatedControlID="to_date" Text="To:" runat="server" />
    <asp:TextBox ID="to_date" CssClass="to_date" Text="" runat="server" />
    <asp:Label ID="log_lbl" CssClass="log" runat="server" />
    </form>

ASPX.CS
using System;
using System.Web.Services;

public partial class _Default : System.Web.UI.Page
{
    [WebMethod]
    public static string GetDate(string fromDate, string toDate)
    {
        DateTime dtFromDate;
        DateTime dtToDate;

        // Try to parse the dates
        if (DateTime.TryParse(fromDate, out dtFromDate) &&
            DateTime.TryParse(toDate, out dtToDate))
        {
            // Perform calculation and/or database query

            return "success!";
        }

        return null;
    }
}


Inconsistent solution to differential equation

Question: $Q.$
Let f(x) be a continuous function satisfying the following differential equation-
$$f(x)=(1+x^2)(1+\int_0^x\frac{f^2(t)dt}{1+t^2})$$
$$\text{Find  f(1)}$$
My Work-
1)Putting $x=0$ in the equation we get $f(0)=1$
2)Dividing by $1+x^2$ and differentiating w.r.t. $x$ we get-
$$(\frac{y}{1+x^2})'=\frac{y^2}{1+x^2}\qquad\text{∴ y=f(x)}$$
Simplifying-
$$y'(1+x^2)-2xy=y^2(1+x^2)$$
so either $f(x)=0$ or
$$\frac{-dy(1+x^2)}{y^2}+\frac{2xdx}{y}=(-1-x^2)dx$$
$$\frac{d}{dx}(\frac{1+x^2}{y})=\frac{d}{dx}(-x-\frac{x^3}{3})$$
$$\frac{1+x^2}{y}=-x-\frac{x^3}{3}+c$$
Using $y(0)=1$ we get $c=1$ and hence $$f(1)=-6$$
My issue- looking at the question, no matter the value of f(x), the R.H.S. of the equation must always be positive (squared) however the answer is coming to be negative. Am I missing something? Or is there any error in the question? Or is $f(x)=0$ the only acceptable solution?
Comment: See also the same problem at https://math.stackexchange.com/questions/3776556/solve-the-following-de-and-hence-find-fx and https://math.stackexchange.com/questions/2282167/differential-equation-one-question-two-methods-both-result-in-different-answ, the last an exact duplicate. There is no such function $f$ with a domain that includes $x=1$. The solution has a pole at about $x=0.817732..$
Comment: Oh, @LutzLehmann, I did not see your comment before posting my answer. If you post a similar one, I can remove mine.
Answer: $$\frac{f(x)}{1+x^2}=1+\int_{0}^{x} \frac{f^2(t)}{1+t^2}dt \implies f(0)=1$$
D. w.r.t. $x$, using Lebnitz, to get
$$f'(x)-\frac{2x}{1+x^2}f(x)=f^2(x)\implies f^{-2}f'-\frac{2x}{1+x^2}\frac{1}{f}=1$$
This is Bernoulli equation. Let $1/f=v$, then we get
$$\frac{dv}{dx}+\frac{2x}{1+x^2}v=-1$$
This is linear equation, whose integrating factor is $I=\exp[\int \frac{2x}{1+x^2}dx]\implies I= (1+x^2)$
$$v=(1+x^2)^{-1} \int -1(1+x^2) dx + C (1+x^2)^{-1}.$$
$$\implies v=\frac{-x-x^3/3}{1+x^2}+C(1+x^2)^{-1}=\frac{1}{f}$$
Used $f(0)=1 \implies C=1.$ Finally, $$f(x)=\frac{1+x^2}{1-x-x^3/3}.$$
So $f(1)=-6.$ The plot of $f(x)$ is given below wherein $f(x)>0$only in (0,0.8177.. ), then there is a singularity at $x=0.8177..$ and it becomes negative. The answer to OP's interesting question could lie in the non-linearity of this ODE.
Comment: What if i bound the domain so it no longer contains the singularity? That still doesn't explain why the function comes out negative even with that R.H.S. point.
Comment: @Etotheipi : What do you mean with "bound"? If you restrict $f$ to, for example, the interval $[0,0.81]$ where it is continuous, then the value $f(1)$ at $x=1$ is undefined, as outside of the domain.
Answer: Your solution of the integral equation looks fine to me, and your observation about the sign is good.
The problem is that the solution blows up when $x^3+3x-3=0$, which happens when $x$ approaches $0.82$, approximately.
Comment: How does it matter if a singularity exits? We are only concerned with the value of f at x=1 so how would it affect the value?


IE innerHTML chops sentence if the last word contains '&' (ampersand)

Question: I am trying to populate a DOM element with ID 'myElement'. The content which I'm populating is a mix of text and HTML elements.
Assume following is the content I wish to populate in my DOM element.
var x = "Success is a matter of hard work &luck";

I tried using innerHTML as follows,
document.getElementById("myElement").innerHTML=x;
This resulted in chopping off of the last word in my sentence.
Apparently, the problem is due to the '&' character present in the last word. I played around with the '&' and innerHTML and following are my observations.

If the last word of the content is less than 10 characters and if it has a '&' character present in it, innerHTML chops off the sentence at '&'.
This problem does not happen in firefox.
If I use innerText the last word is in tact but then all the HTML tags which are part of the content becomes plain text.

I tried populating through jQuery's #html method,
 $("#myElement").html(x);

This approach solves the problem in IE but not in chrome.
How can I insert a HTML content with a last word containing '&' without it being chopped off in all browsers?
Update : 1. I tried html encoding the content which I am trying to insert into the DOM. When I encode the content, the html tags which are part of the content becomes plain string.
For the above mentioned content, I expect the result to be rendered as,
Success is a matter of hard work &luck
but when I encode what I actually get in the rendered page is,
Success is a matter of hard work &luck
Answer: You should replace your & with &.
The & (ampersand) character is used within HTML to represent various special characters. For example, " = ", < = <, etcetera. Now, &luck clearly is not a valid HTML entity (for one it is missing the semicolon). However, various browsers may, due to combinations of error correcting (the semicolon), and the fact that it looks somewhat like an HTML entity (& followed by four characters) try to parse it as such.
Because &luck; is not a valid HTML entity, the original text is lost. Because of this, when using an ampersand in your HTML, always use &.
Update: When this text is entered by a user, it is up to you to escape this character properly. In PHP for example, you would call htmlentities on the text before displaying it to the user. This has the added benefit of filtering out malicious user code such as


an abstract algebra question: how to prove there exists a subgroup whose order is K

Question: If k is an odd and positive integer, please prove that any group whose order is 2k has a subgroup whose order is k.
I have been struggling for this, I tried to use mathematical induction to prove it, but maybe it doesn't work. Can someone help me solve this question? thank you for your help.
Answer: Consider the left regular action of $G$ on $G$. When seen as a homomorphism of $G$ to $S_G$ the  image of $g$ is an odd permutation if and only if $\frac{|G|}{|g|}$ is odd. Notice when $G$ is of order $2k$ there is an element of order $2$ by Cauchy. So the image of the homomorphism has odd permutations. A subgroup of a symmetric group can half either exactly half odd permutations or no odd permutations.
Since in this case there is at least one odd permutation you can consider the preimage of the even permutations and use the first iso theorem to prove it has the desired order.
Comment: I realise I could have been clearer when writing. If you need clarification feel free to ask.
Answer: Let $G$ be a group of order $2k$ where $k$ is odd. By Cayley theorem we can see $G$ as a subgroup of $S_{2k}$.
Let $a\in G$ such that $|a|=2$ and $G=\{g_1,g_2,...,g_{2k}\}$ then notice that $a$ correspond to product of cylces $(g_1,ag_1)(g_2,ag_2),...(g_k,ag_k)$ thus $a$ correspond to  an odd permutation.
As $G $ is not contained in $A_{2k}$ then $GA_{2k}=S_{2k}\implies G/(A_{2k}\cap G)\cong S_{2k}/A_{2k}=Z_2$
Thus, $G\cap A_{2k}$ has index $2$ in $G$.
Comment: This is nice, I had never used Cayley before in order to skip stating the homomorphism. +1
Comment: @JorgeFernández: Thank you


kendo treeview head node from child

Question: I have a kendo treeview i use this function to bind event change
   change: function (e) {
        if (e.field == "checked") {
            gatherStates(e.items);
            alert(e.items);
        }
    }

If i want to know the 'dad node'(the node that contain the selected child) of the selected child?
Answer: You can get the parent node from e.node:
tree.dataSource.bind("change", function (e) {
    if (e.field == "checked") {
        var node = e.items[0];
        console.log("node", node.text);
        console.log("parent", e.node.text);
    }
});

Example here (http://jsfiddle.net/OnaBai/ECnef/)
Comment: Yes thank you i have seen the function .parentNode() e.item.parentNode()
Comment: if i want to bind the same evento in kendo grid? so in kendo grid i want to bind in change the checked event..  i have a checkbox column.
Comment: Sorry, I do not understand your question. Would you mind rephrasing it?
Comment: in the treeview i bind the checked event with the code upside  "if(e.field == "checked")"    with the kendo grid for binding the checked event in the 'change event' there is a same method of that i use in the treeview? { i want to bind a checked event in kendo grid }
Answer: i have a same kind of issue with kendo treeview checkboxes in IE8
jQuery("#treeview").kendoTreeView({
    dataSource: ss,
    dataTextField: ["ss_"],
    checkboxes: {
        checkChildren: true
    },
    select: function (e) {
        jQuery(e.node).find("input")[0].click();
    }
});

var treeview = jQuery("#treeview").data("kendoTreeView");
treeview.expand(".k-item");
treeview.dataSource.bind("change", onCheckboxClicked);

selecting the text of checkbox fires the select event of treeview and in this event i click the checkbox manually (my requirements)...which in turn fires change event of data source in IE-9. But it doesn't fire the change event of datasource in IE-8. What is the issue?
Thanks

kendo treeview head node from child


Number of integral values of $x\in (\frac{\pi}{2},5\frac{\pi}{2})$ such that $\max(x^2+\cos x-1,1-x^2-\cos x)=\max(\cos x+x^2-1,x^2-1-\cos x)$

Question: The number of integral values of $x\in(\frac{\pi}{2},5\frac{\pi}{2})$ such that
$$\max(x^2+\cos x-1,1-x^2-\cos x)=\max(\cos x+x^2-1,x^2-1-\cos x)$$ is satisfied is... ?
I understand that $\max(x,-x)=|x|$ but I could not simplify the right hand side of the equation.Please help me in this regard. Thanks.
Answer: For $x\in (\frac{\pi}{2},\frac{5}{2}\pi)$, we have that
$$\begin{align}(x^2+\cos x-1)-(1-x^2-\cos x)&=2(x^2+\cos x-1)\\\\&\ge 2(x^2-2)\\\\&\gt 2\left(\left(\frac{\pi}{2}\right)^2-2\right)\\\\&=\frac{1}{2}(\pi^2-8)\\\\&\gt 0\end{align}$$
and that
$$(\cos x+x^2-1)-(x^2-1-\cos x)=2\cos x\begin{cases}
\lt 0 & \text{if}\ x\in (\frac{\pi}{2},\frac{3}{2}\pi)\\[2ex]
\ge 0  & \text{if}\ x\in[\frac{3}{2}\pi,\frac{5}{2}\pi)
\end{cases}
$$
For $x\in (\frac{\pi}{2},\frac{3}{2}\pi)$, the equation can be written as
$$x^2+\cos x-1=x^2-1-\cos x,$$
i.e.
$$\cos x=0$$
which does not hold.
For $x\in[\frac{3}{2}\pi,\frac{5}{2}\pi)$, the equation can be written as
$$x^2+\cos x-1=\cos x+x^2-1$$
which always holds.
Therefore, the answer is $\color{red}{3}$. ($x=5,6,7$)
Answer: two possibilities. if the first part of LHS is greater then, the values of $x$ for which $cos(x)\,> -cos(x)$ are solutions. that is $5\,,\,6$.
 second possibility is second part of LHS and RHS are equal and greater than first part. there are two values for which second parts of max functions are equal and none of them are in the interval. hence there are only two values of x in the given interval which satisfy the equation namely, $5\,,\,6$. by  first part and second part I mean first  and second inputs to max function respectively.


Need help identifying this scale

Question: Yesterday my friend sent me a recording of a song. I was particularly stunned and interested in a scale (maybe not a scale, but it does sound like one.) I decided to upload the scale here: https://soundcloud.com/kris-pianist/scale. Trying my best, I cannot transcribe it. Can anybody please help me?
Comment: Drop the sound file into Audacity, calculate the FFT for each note,  and you're done.
Answer: Yes, basically both hands play an Abmin(maj9) arpeggio, the right in 16ths while the left in 8ths.
Here is the transcription fot it:

Talking about scales, from this excerpt it can be either an Ab melodic minor or an Ab harmonic minor scale.
Comment: OK, so how did you generate this transcription?
Comment: Piano + Ears :D The score is written with Sibelius 7.
Answer: It's not a scale, it's a five-note-arpeggio. It is an Abminmaj9 ('A flat minor major nine') arpeggio. This chord has the notes
Ab Cb Eb G Bb
And on the recording it is played like this (from high to low):
Bb Ab G Eb Cb (and continued like this through 3 lower octaves)
The last note of the arpeggio (Cb, after descending 3 octaves) resolves to Bb, which is the root of the next chord (Bb major).
Comment: An arpeggio is done over a scale, so it is a scale indeed :)
Comment: @m0skit0: Forgive me, but your comment doesn't make a lot of sense :)

Need help identifying this scale


Ranking by date in SQL but ignoring dates <3 days together

Question: I would like to rank some data by date to obtain a sequential list (1, 2, 3) but ignore dates that are <3 days together.
For example:
11/10/2015 = 1
11/11/2015 = 2
11/12/2015 = NULL (within 3 days of previous date)
11/15/2015 = 3

What is an efficient way of doing this please? Thank you in advance.
Comment: Which DBMS are you using? Postgres? Oracle?
Comment: Microsoft SQL Server 2008 R2
Answer: This is a bit challenging, because you don't have lag() or cumulative sum.  But, you can implement it using outer apply (or a subquery):
select e.*,
       (case when CountFlag = 1
             then row_number() over (partition by CountFlag order by e.date)
        end) as newcol
from example e outer apply
     (select top 1 (case when e.date >= dateadd(day, 3, e2.date) then 1 else 0 end) as CountFlag
      from example e2
      where e2.date < e.date
      order by e2.date desc
     ) eprev;

This uses a logic trick to get the NULL value.  Notice there is no WHERE, so all values are assigned a rank.  The outer query uses the same column for the case condition and for the partition by clause.
Comment: This creates NULL in the newcolumn when two dates are the same
Comment: Replace the `<` with `<=` in the subquery.
Comment: OK thanks. How do I do this separately for each person (id) in a dataset, by partitioning? Can this be combined with partition?
Comment: @user2964644 . . . By adding something like `e2.person = e.person` in the subquery.
Answer: I think you're going for something like this. Knowing the RDBMS would help.
with date_lags as
    (
        select
            date,
            lag(date) over(order by date) as last_date
        from
            table
    )
select
    date,
    rank() over(order by date) as the_rank
from
    date_lags
where
    datediff(day, last_date, date) >= 3;

Comment: Microsoft SQL Server 2008 R2


How to get dashed line (with down arrow icon) SVG animation on accordingly scroll?

Question: How can I add a down icon (Small) in the dotted line? Can you help me, please? Like this line:- How to get dashed line svg animation on accordingly scroll?
Just have to add some down arrow in the dotted line.
Comment: It's not very clear what is required. Could you put in your code so far and show what you have tried to add an arrow and describe where the arrow is to be in relation to the animated line.
Answer: You can position an arrowhead shape at the head of the animated line by use the path.getPointAtLength() method.
Below is a cleaned-up version of the code you link to, with a bit of additional code to add the arrowhead and position it correctly as the scroll animation happens.

var path = document.getElementById("thePath");
var mask = document.getElementById("maskPath");
var arrow = document.getElementById("arrowhead");

var pathLength = path.getTotalLength();

// Initialise the mask dash pattern to patch the actual path length
mask.style.strokeDasharray = pathLength;

window.addEventListener("scroll", myFunction);

function myFunction() {
  var scrollpercent = (document.body.scrollTop + document.documentElement.scrollTop)
                      / (document.documentElement.scrollHeight - document.documentElement.clientHeight);
  var len = pathLength * scrollpercent;
  drawPathLength( len );
  drawArrowAtLength( len );
}

function drawPathLength(len) {
  mask.style.strokeDashoffset = pathLength - len;
}

function drawArrowAtLength(len) {
  // Get the x,y coordinates of the path at length "len"
  var pos = path.getPointAtLength(len);
  // Reposition the arrowhead at that position
  arrow.setAttribute("transform", "translate(" + pos.x + "," + pos.y + ")");
}

// Initialise the amount of drawn path to 0
drawPathLength(0);
// Initialise the arrowhead position to the start of the path
drawArrowAtLength(0);

Scroll down

<svg width="198px" height="1483px" viewBox="0 0 198 1483">
  <defs>
    <linearGradient x1="50%" y1="0%" x2="50%" y2="100%" id="linearGradient-1">
      <stop stop-color="#DE1652" offset="0%"></stop>
      <stop stop-color="#F37121" offset="50.2239948%"></stop>
      <stop stop-color="#FBAB26" offset="100%"></stop>
    </linearGradient>

    <path id="thePath"
      d="M702,266 C682,424 795.064639,474.307498 716,600 C599,786 769,821 688,988 C548.560405,1275.48657 822.815807,1223 840.843207,1373 C858.870608,1523 605.485477,1528 687.610302,1728"
      transform="translate(-646, -266)"
      fill="none" />

   <mask id="theMask" maskUnits="userSpaceOnUse">
      <use id="maskPath" xlink:href="#thePath"
           stroke="#fff" stroke-width="8" />
    </mask>
  </defs>

  <use id="visiblePath" xlink:href="#thePath"
       stroke-width="4"
       stroke-dasharray="12 16"
       stroke="url(#linearGradient-1)"
       mask="url(#theMask)" />

  <g transform="translate(-646, -266)">
    <polygon id="arrowhead"
             points="-10,0, 0,20, 10,0"/>
  </g>

</svg>


WTS: $X^{-1}(\mathcal{F}(\mathcal{A})) \subset \mathcal{F}(X^{-1}(\mathcal{A}))$ to finish proof.

Question: I'm stumbling over the second step in a proof that $X^{-1}(\mathcal{F}(\mathcal{A})) = \mathcal{F}(X^{-1}(\mathcal{A}))$, where $X: \Omega \to \Theta$ and $\mathcal{A}$ is a collection of subsets of $\Theta$.
(Note: $\mathcal{F}(\cdot)$ generates the smallest $\sigma$-algebra for $\cdot$)
I already have $\mathcal{F}(X^{-1}(\mathcal{A})) \subset X^{-1}(\mathcal{F}(\mathcal{A}))$, but I don't see the other direction. (That step isn't so clear in the text I'm reading.)
Answer: Hint:

Show that for any $\sigma$-algebra $\mathcal{M}$ the family $$\Sigma := \{A \in \mathcal{F}(\mathcal{A}); X^{-1}(A) \in \mathcal{M}\}$$ is a $\sigma$-algebra.
Choose $\mathcal{M} := \mathcal{F}(X^{-1}(\mathcal{A}))$. Show that $\Sigma$ contains $\mathcal{A}$.
Conclude that $\mathcal{F}(\mathcal{A}) \subseteq \Sigma$.
Comment: Thanks! This was very similar to the proof I was reading, but your second step really helped.
Comment: @zxmkn You are welcome.


Datatables - How can i use an array as SQL where clause

Question: I'm trying to make a Datatable that dynamically loads data based on the user's settings.
On the server processing script
I have an array of branches owned by the current user.
<code>$branchesOwned = $db->query('SELECT branchId FROM zapp_clt_branchesowner WHERE ownerId = ?', $ownerId)->fetchAll();
</code>
So far so good!
i tried to create a secondary array where i would store the branchId from the 1st array :
<code>$whereArray = [];

foreach ($branchesOwned as $result) {
array_push($whereArray, $result['branchId']);
}
</code>
now on the SSP complex i have this:
<code>//$whereAll = "status = 'B Activo' AND branchID IN ('1')"; <--- WORKING
$whereAll = "status = 'B Activo' AND branchID IN {$whereArray}"; // <--- NOT WORKING

echo json_encode(
SSP::complex( $_GET, $sql_details, $table, $primaryKey, $columns, $whereResult = null, $whereAll)
);
</code>
As you can see if it write the array directly in the $whereAll it works
Answer: You can do something like this:
<code>$idsAsString = sprintf("('%s')", implode("', '", $whereArray));

$whereAll = "status = 'B Activo' AND branchID IN $idsAsString";
</code>


Deprecated: mysql_connect() Error Code

Question: My host recently upgrade the PHP version and a certain part of my website now shows the following error:
Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in url/structure/here on line 49

That is referencing the below code:
function DBConnect() {
    $this->connectCount ++;
    //echo "$this->connectCount
";

    if ($this->dbType == 'mysql') {
        $dbConnect = mysql_connect($this->dbHost, $this->dbUser, $this->dbPasswd) or die ("MySql Connection Failed: " . mysql_error());
        mysql_select_db($this->dbName, $dbConnect);
    }

    if ($this->dbType == 'postgresql') {
        $dbConnect = pg_connect("host=$this->dbHost port=$this->dbPort dbname=$this->dbName user=$this->dbUser password=$this->dbPasswd") or die ("PostgreSQL Connection Failed: " . pg_errormessage($dbConnect));
        //$dbConnect = pg_pconnect("host=$this->dbHost port=$this->dbPort dbname=$this->dbName user=$this->dbUser password=$this->dbPasswd") or die ("PostgreSQL Connection Failed: " . pg_errormessage($dbConnect));
    }

    return $dbConnect;
}

I'm aware the fact that this is because the current way my site connects to MYSQL is now outdated in the new version of PHP but does anyone know how I would update the above code to make this work?
Comment: The easiest way is probably to use `mysqli_` which has very similarly named functions. Check out the [docs](http://php.net/manual/en/book.mysqli.php).
Comment: http://php.net/manual/en/function.mysql-connect.php
Comment: I would go ahead and migrate to PDO: http://www.sitepoint.com/migrate-from-the-mysql-extension-to-pdo/
Answer: The easier way is to use mysqli_connect(). The syntax is very similar to what you would had with mysql_connect(),which means the changes in your code will be minor and easy to make.
Pdo would be the safest, but if you are trying to get you site back on quickly, the mysqli_* commands will achieve that.
Google (or check on stackoverflow) mysql vs mysqli. You ll find plenty of examples.
Hope this helps.
Good luck
--
Sorry after re-reading i see you asked what needs to be change on your source code. Afraid i cannot help right now as i am responding from a mobile phone :(

Deprecated: mysql_connect() Error Code


Discrete Fourier Transform, overly large zero-frequency term

Question: After looking around this website and many others, I've been able to figure out most of how to reconstruct my time-domain data by using the discrete fourier transform. (http://www-elsa.physik.uni-bonn.de/~dieckman/DFT/DFT.html was quite helpful.)
BUT: I cannot figure out why the s=1 term of my transformed frequency data is so overly large when compared to the rest. This question describes that the first term is an average of the data, but then the value should be approximately 1/50th of what the DFT yields.
Here's a snippet of the first bit of the time domain and resultant frequency domain vectors:
Time: {0.12545, 0.093577, 0.083911, 0.07649, 0.080237, 0.112101, 0.112242, 0.137024, 0.143058, 0.131691, 0.117775, 0.096736, 0.08467, 0.078244,
0.08896, 0.099834, …}
(modulus of) Frequency: {2.87325, 0.0447267, 0.0945387, 0.0535332, 0.0138847, 0.0161506, 0.0278486, 0.0229005, 0.0912012, 0.0123259, 0.03707, 0.0396228, 0.0781733, 0.0263154, 0.0117688, …}
My data is has n=500, timestep=1. I've been working with the data in Mathematica, but I don't believe the issue is with how I'm using Mathematica.
I'm really at a loss as to what would be causing such a huge offset frequency term. If I ignore it and just try to determine the shift manually, everything works fine! But...that's not good practice. I also had to omit it when calculating the periods of my modes, which isn't good practice either. So any explanations as to why the real-frequency is abnormally large and/or suggestions on how to approach it would be welcomed!
Comment: The paper you cite uses a $\sqrt n$ scaling.  Accordingly, the 0 frequency term should be $64.2477/\sqrt{500}=2.87324$, which is pretty much what your report as the result.  So I don't understand your question: the 0 freq component seems to be exactly what you'd expect.
Comment: What is the sum of your 500 time-domain points?
Comment: The sum of the time domain points is 64.2477, which is actually a number I recognize as the zero-frequency term from when I did the FT with parameters {1,-1}.

So it is related to that sum, somehow. I tried to take the average manually, and that does yield a number very similar to the one I originally generalized as the shift. So that question helped a lot.

My question now, is....why is it showing up as the sum and not the average, mathematically?
Comment: I think the default FT scaling used by Mathematica is the $\sqrt n$ scaling you observe.  The post you mention in your 2nd paragraph uses $n$ scaling.  Whenever I use an FT software for the first time, I check it on test cases to make sure the scaling and sign in the exponent are as I expect.
Comment: So just to ensure I'm understanding this correctly:
The first term is a sum of all of the numbers in my time vector because the weighting factor of the exponential will equal 1, since s=1 --> e^0, whereas for all other terms the weighting factor is obviously much less than 1.

I guess what I need to look into is why there are different scalings, where you say Mathematica uses the sqrt(n) scaling and apparently my data requires an n scaling to match with the other frequency data output by the FT? It's at least a place for me to focus on, thank you!
Comment: No. The paper you cite (http://www-elsa.physik.uni-bonn.de/~dieckman/DFT/DFT.html) gives a formula, which as far as I know is what your computer evaluated.  The a-th frequency is the sum of the b-th data point times a term of form exp(2pi*i*a*b/500) divided by sqrt(500).  In the special case of the 0-th frequency this reduces to the sum of the data values, divided by sqrt(500).
Answer: Thanks to @kimchi lover, I think I'm able to understand what is going on now.
Mathematica uses the formula
$$
v_s=\frac{1}{n^{1/2}}\sum^n_{n=1}u_r e^{2\pi i(r-1)(s-1)n}
$$
to evaluate the Fourier Transform of the time domain vector $u_r$, which yields a vector of equal length containing frequencies, $v_s$. The zeroth frequency, at $v_1$, is equal to $\frac{1}{n^{1/2}} \sum^n_{n=1} u_r$, so the sum of the time domain vector divided by the square root of the number of points. In my case, it just happens that since all my points are positive, I end up with a large zeroth frequency value.
The math still works out. When I apply that the zeroth frequency $v_1$ is related to the amplitude via $\sqrt{n}$: $v_1=A_0\sqrt{n}$, then the 'offset' is equal to $A_0=\frac{v_1}{\sqrt{n}}$, or $A_0=\frac{\sum^n_{n=1}u_r}{n}$, which was part of my confusion regarding different scalings.


Foreign keys with mysql is it possible to have a foreign key based on value of column?

Question: I have this database structure,
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";

CREATE TABLE IF NOT EXISTS `announces` (
   `tracker` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
   `failCount` smallint(5) unsigned NOT NULL DEFAULT '0',
   PRIMARY KEY (`tracker`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

CREATE TABLE IF NOT EXISTS `hashes` (
   `hash` binary(20) NOT NULL,
   `indexed` tinyint(1) NOT NULL DEFAULT '0',
   PRIMARY KEY (`hash`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

CREATE TABLE IF NOT EXISTS `trackers` (
   `hash` binary(20) NOT NULL,
   `tracker` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
   `seeders` mediumint(8) unsigned NOT NULL DEFAULT '0',
   `leechers` mediumint(8) unsigned NOT NULL DEFAULT '0',
   KEY `hashFK` (`hash`),
   KEY `trackerFK` (`tracker`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

ALTER TABLE `trackers`
   ADD CONSTRAINT `hashFK` FOREIGN KEY (`hash`) REFERENCES `hashes` (`hash`)
   ON DELETE CASCADE,
   ADD CONSTRAINT `trackerFK` FOREIGN KEY (`tracker`) REFERENCES `announces` (`tracker`)
   ON DELETE CASCADE;

The table trackers has 2 foreign keys one for trackers, and one for hashes.
This I think makes sure that a hash cannot be in trackers without first being in hashes. And if a hash is deleted from hashes then it also gets deleted from trackers.
Same for trackers, a tracker must exist in announces before it can exist in trackers, and if it gets deleted from announces it also gets deleted from trackers.
The problem I have is that a hash should only exist in trackers if the corresponding value of indexed in the hashes row is == 1. Is this possible?
Comment: would you like to set indexed = 1 onto the hash whenever a tracker is inserted with a fk toward it? Or maybe you'd prefer to raise an error whenever a tracker is inserted with a fk to a hash with indexed != 1?
Comment: Preferably the latter, as far as I understanded the manual I didn't think I could add triggers with foreign keys? thanks
Answer: If what you wish is to raise an error whenever a tracker is inserted with a fk to a hash with indexed != 1, then it has to be implemented at the applicative layer.
Various options:

favorite coding language checks (subsequent queries to check values before insertions)
using triggers, before insert into tracker, check that the corresponding hash is indexed, and if not cancel/raise error

cheers
Comment: But maybe a more global analysis should be performed? Maybe whenever a hash is indexed it should have a tracker immediatly inserted with? Maybe when the user decides to create a tracker from a hash, he should only have the choice of selecting indexed hashes? I don't know the nature of your system but you got my point.
Comment: Ye this makes sense, just gonna have to tweak alot of things to get it to work :)


Prove the identity $\csc2\theta=\frac{\sec\theta\csc\theta}{2}$

Question:
Prove the identity $$\csc2\theta=\frac{\sec\theta\csc\theta}{2}$$

I've started by using a double angle identity, but I'm not sure how to continue from here or if this is right approach.
$$\csc2\theta=\frac{1}{\sin2\theta}=\frac{1}{2\sin\theta\cos\theta}$$
Comment: Your left-hand side should be $\csc (2\theta)$
Answer: What you did is correct. Now, you do:$$\frac1{2\sin\theta\cos\theta}=\frac{\frac1{\cos\theta}\times\frac1{\sin\theta}}2=\frac{\sec\theta\csc\theta}2.$$
Answer: Your approach is right, you just need to do the last step to get the desired result: What are $\frac{1}{\sin(\theta)}$ and $\frac{1}{\cos(\theta)}$?
Answer: The thing you did is OK. The question which occurs is do you know how to prove $$\sin (2x) = 2\sin x \cos x$$
(Hint: use adition theorem for function $\sin $)
Answer: You are already on the right track. Here is another approach.GO!
$$\begin{aligned}\csc{2\theta}&=\frac{1}{\sin{2\theta}}\\&=\frac{1}{2\sin\theta\cos\theta}\\&=\frac12\csc\theta\sec\theta\\&=\frac{\csc\theta\sec\theta}{2}\end{aligned}$$
I hope this helps.


how can i reduce the lines of code which are under different conditions

Question: snippet is  as below:
@api.route('/<graphType>/<fieldType>')
def display1(graphType,fieldType):
    dbconnection = dbconnector.configuration('farmautomation')
    if graphType == "line" and fieldType == "weather details":
        dataframe_name = DataFrame_Conversion.weather_details_dataFrame(dbconnection)
        groupbyvalue = 'village'
        fieldstoaggregate = 'humidity'
        datamin, datamax = Groupby.groupby(dataframe_name, groupbyvalue, fieldstoaggregate,
                                           field='humidity')
        return Graphs.weather(datamin, datamax)

    elif graphType == "pie" and fieldType == "total farmers":
        dataframe_name = DataFrame_Conversion.logins_time_dataFrame(dbconnection)
        groupbyvalue = 'created_time'
        fieldstoaggregate = 'count'
        result = Groupby.groupby(dataframe_name, groupbyvalue, fieldstoaggregate,
                             field='logins')
        return Graphs.pie(result)
    elif graphType == "bar" and fieldType == "logins":
        dataframe_name = DataFrame_Conversion.logins_time_dataFrame(dbconnection)
        groupbyvalue = 'created_time'
        fieldstoaggregate = 'count'
        result = Groupby.groupby(dataframe_name, groupbyvalue, fieldstoaggregate,
                                 field='logins')
        return Graphs.bar(result)

The code inside both the condition's(elif's) are same but have different return type, is there a possibility to reduce my code?
I have got no idea to try someway, any help is appreciated
Comment: @dmitryro can you please put up as an answer? still got stuck mate!!
Comment: your current code does not return anything on 2nd branch of the conditional
Comment: sorry, i missed it !!, thanks i will update
Comment: Can you have that conditional in more than one place within your application?
Comment: you mean putting those conditions outside of routes?
Comment: I mean: could those conditionals be applied/occurred in different places of the application (not just in a single route handler)?
Comment: No, Not actually ,In my case user selects graphtype and field type and if they match the condition goes on,.....
Answer: Looks like the 2nd and 3rd conditions are essentially the same, so they could be combined as such:
@api.route('/<graphType>/<fieldType>')
def display1(graphType,fieldType):
    dbconnection = dbconnector.configuration('farmautomation')
    if graphType == "line" and fieldType == "weather details":
        dataframe_name = DataFrame_Conversion.weather_details_dataFrame(dbconnection)
        groupbyvalue = 'village'
        fieldstoaggregate = 'humidity'
        datamin, datamax = Groupby.groupby(dataframe_name, groupbyvalue, fieldstoaggregate,
                                           field='humidity')
        return Graphs.weather(datamin, datamax)

    elif graphType in ['pie','bar'] and fieldType in ['logins','total farmers']:
        dataframe_name = DataFrame_Conversion.logins_time_dataFrame(dbconnection)
        groupbyvalue = 'created_time'
        fieldstoaggregate = 'count'
        result = Groupby.groupby(dataframe_name, groupbyvalue, fieldstoaggregate,
                             field='logins')
        if graphType == 'pie':
            return Graphs.pie(result)
        else:
            return Graphs.bar(result)

There might be a better way yet to refactor, but it depends on if you have more (lots of) cases to test or just these few.
EDIT1: Fixed total farmers string
EDIT2: Based on additional comment/question about lots of paths, added another structure that might work.
Disclaimer: I'm relatively new to Python and this code has not been tested, but the general idea is to consolidate the unbounded parts of your problem to a single spot - in this case a Dictionary - so that you have a single source of truth for that part.
@api.route('/<graphType>/<fieldType>')
def display1(graphType,fieldType):
    # Open your db connection
    dbconnection = dbconnector.configuration('farmautomation')
    # Get your chart data based on selection
    chart_args = get_aggregate_data(fieldType, dbconnection)
    # Try to get a chart with that data
    chart = get_chart(graphType, chart_args)

    if chart != None:
      return chart
    else:
      # Throw an error, return None - your callable
      pass

class AggregationSettings:
  def __init__(self, df_name='', group_by='',
       fields_to_agg='', over_field=''):
    self.df_name = df_name
    self.group_by = group_by
    self.fields_to_agg = fields_to_agg
    self.over_field = over_field

# This dictionary is what will grow as you add routes
DATAFRAME_TRANSLATE = {
  "weather details":AggregationSettings("weather_details","village","humidity","humidity"),
  "logins":AggregationSettings("logins_time","created_time","count","logins"),
  "total farmers":AggregationSettings("logins_time","created_time","count","logins")
}

def get_aggregate_data(fieldType, db_connection):
  agg_setting = DATAFRAME_TRANSLATE.get(fieldType, None)
  if agg_setting == None:
    # not in the dict
    raise ValueError('The specified fieldType is not valid')

  df_val = agg_setting.df_name + '_dataFrame'
  # NOTE: I'm not familiar with pandas (which I think this is), but I
  # suspect there is a way for you to get your return value passing the
  # name, not the class explicitly.  If not, there are ways around that too
  dataframe_name = DataFrame_Conversion.get_by_name(df_val, db_connection)
  return Groupby.groupby(dataframe_name, agg_setting.group_by,
                        agg_setting.fields_to_agg, agg_setting.over_field)

def get_chart(graphType, chart_args):
  # I expect the number of charts is small(ish) and bounded,
  # so just use if/else hex
  if graphType == 'pie':
    return Graphs.pie(chart_args)
  elif graphType == 'bar':
    return Graphs.bar(chart_args)
  else:
    # handle other cases as needed...
    pass

  raise ValueError('The specified graphType is not valid')

Comment: only change to this answer is, fieldType in ['logins','total farmers'], thanks @Mikah Barnett
Comment: Sorry, was doing it quickly and mis-typed the literal, fixed now.
Comment: @Codenewbie I added another section that is how I would approach building something that could handle something like 100 route combos.  I'm not an expert, but I think this would get you to a more stable, maintainable bit of code.
Comment: Is this a better approach, i mean writing conditions , because if there are like 100 cases?
Comment: First of all I would like to thank you for all the above idea ,One thing I want to mention is, end user selects the graphType and fieldType and if the combination matches then perform whole set of operations. But now I changed it as, user selects the graphName and then based on name the operations goes on!!
Comment: Here I mentioned field='somevalue' just to differentiate in Groupby.groupby class Groupby():

    def groupby(dataframe_name, groupbyvalue, fieldstoaggregate,field):
        if field=='humidity':
            datamin = dataframe_name.loc[dataframe_name.groupby([groupbyvalue])[fieldstoaggregate].idxmin()]
            datamax = dataframe_name.loc[dataframe_name.groupby([groupbyvalue])[fieldstoaggregate].idxmax()]
            return (datamin,datamax)


Options for sending data between two computers over the internet

Question: My problem is fairly simple: I wish to send/receive simple commands between two PCs. The first PC (PC1) runs a program that controls and monitors an alarm system. The seconds PC (PC2) is any PC that is connected to the internet and must be able to also control and monitor the alarm system.
A Java program runs on PC1 and this program monitors and controls the alarm. I therefore have to find a way to control this program remotely. I do not want to use remote desktop as I need to limit the amount of data transfer. I just want to be able to send/receive commands to/from PC1. The program on PC2 can either be a stand alone program or a web app. I'm not sure what would be the best/easiest option to implement. Any comments would be appreciated.
So far, I have come up with the following options:

PC1 acts as a server and opens a socket for the PC2. PC2 connects to the sockets and starts to send commands and then receives responses. I think firewalls and IP addresses can be be a problem
Create a server program that runs on a server on the internet somewhere. PC1 and PC2 would then be clients that communicate with each other via the server. I think this is the best solution, but I have no idea how to implement this.
Use Google App Engine as the server and somehow relay information between the two PCs.

I've done a lot of research, bit still I don't know what is the best way to implement this. I am planning on writing the programs in Java. I have good programming experience, but my knowledge regarding networks are very limited. I would also have the add a password to log in and ideally encrypt the transmitted information.
Any comments regarding the above options or any other method to solve my problem would be greatly appreciated.
Thanks
Comment: This really seems more of a question for stackoverflow instead of serverfault
Answer: Depending on the design of the Java program and the oporating system you are working with the solutions might already be at your finger tips. Using something along the lines of SSH to get a command shell on the remote machine that would allow you to send the comands to the alarm monitoring program and veiw the responces would probably be a good starting point. Without more specific information on the enviorment you are working with that is my best advice. If the alarm monitoring program has an API tieing it to a very simple secure client/server interface program would not be too hard.
Comment: I must still write the java program that runs on PC1 as I'm designing the whole system. Let me explain it in a different way: Suppose I have a program that controls the serial port of a PC that is connected to a coffee machine. What would be the easiest/best method to send commands to this program so that I'm able to control the coffee machine via the internet? This is just a simple explanation, but I think the principles are the same. Do you still think SSH is the best solution? Thanks!
Comment: okay well since you are still developing the software you have a world of options. If you want to avoid as many firewall problems with client server as possible then you want something like this. PC1 initiates a connection to a server on the internet the server provides an interface that PC2 can connect to. The interface for PC2 could be a webpage on the server or a socket and API for a clinet program to connect to. The other option would be a simple java client\server application. In eithercase it would be a good idea to encrypt the connection.
Comment: A tried a simple java client/server app and it worked well in my home network, but I had firewall problems when I tried it over the internet, so as you said, the server on the internet would be the best option. Having said that, I have more experience in embedded design and little network knowledge. Where would I start to develop such a server application as I have no idea how to implement this? Where would the app be hosted or can I host it myself? I just need a push in the right direction, I think I'll be able to figure it out from there.
Comment: Think about the internet server this way. On one side it is a server that the client on the alarm monitor connects to and sends information to. On the other side it is a server that the client connects to and gets the informationg that was sent to the server.
Comment: Thanks Liam, I understand that, but how would I actually implement such a solution? 1. How does the clients communicate with the server?  Should I use sockets sockets or http? 2. Can I write the server program in Java or what language should I use? 3. Where can I host this server app? Can I have it running on my own computer or are there companies that provides such a service?


Problem with Kohana 3.2 Validation class. It seems it is not sending Exception when there is an error

Question: When the POST data is send to:
Auth::instance()->register( $_POST );

The data is then validated... If it's not I assume the Validation Class in Kohana throws an Exception. And then try-catch function catches it. The problem I am having is with this method:
$this->send_confirmation_email($_POST);

It is called even if the data is not valid. I believed that if the data was not valid it would skip everything else and jump to catch... But it seems I was wrong because I am getting a nasty Fatal error from the method to send an email because it cannot find the email address...
try {
        if( ! $optional_checks ) {
           //throw new ORM_Validation_Exception("Invalid option checks");
        }

        $_POST['email_code'] = Auth::instance()->hash(date('YmdHis', time()));

        Auth::instance()->register( $_POST );

        $this->send_confirmation_email($_POST);

        // sign the user in
        Auth::instance()->login($_POST['username'], $_POST['password']);

        // redirect to the user account
        $this->request->redirect('user/profile');
     } catch (Validation_Exception $e) {

So, is there a way so that the method to send an email is skip if the data is not valid?
One could say I should use check() method. Here is why it is a problem:
 Validation::factory($fields)
                    ->rules('username', $this->_rules['username'])
                    ->rule('username', 'username_available', array($this, ':field'))
                    ->rules('email', $this->_rules['email'])
                    ->rule('email', 'email_available', array($this, ':field'))
                    ->rules('password', $this->_rules['password'])
                    ->rules('password_confirm', $this->_rules['password_confirm']);

            if (Kohana::config('useradmin')->activation_code) {
                    Validation::factory($fields)->rule('activation_code', 'check_activation_code', array($this, ':field'));
            }

Thanks in advance for any help.
UPDATE:
It seems now that there is a problem with Kohana Validation class.
Here is the method in my Model_User class:
public function create_user($fields)
{
    Validation::factory($fields)
        ->rules('username', $this->_rules['username'])
        ->rule('username', 'username_available', array($this, ':field'))
        ->rules('email', $this->_rules['email'])
        ->rule('email', 'email_available', array($this, ':field'))
        ->rules('password', $this->_rules['password'])
        ->rules('password_confirm', $this->_rules['password_confirm']);
        //->labels($_labels);

    if (Kohana::config('useradmin')->activation_code) {
        Validation::factory($fields)->rule('activation_code', 'check_activation_code', array($this, ':field'));
    }

    // Generate a unique ID
    $uuid = CASSANDRA::Util()->uuid1();

    //CASSANDRA::selectColumnFamily('UsersRoles')->insert($username, array('rolename' => 'login'));
    CASSANDRA::selectColumnFamily('Users')->insert($uuid, array(
                            'username'      => $fields['username'],
                            'email'         => $fields['email'],
                            'password'      => Auth::instance()->hash($fields['password']),
                            'logins'        => 0,
                            'last_login'        => 0,
                            'last_failed_login' => 0,
                            'failed_login_count'    => 0,
                            'created'       => date('YmdHis', time()),
                            'modify'        => 0,
                            'role'          => 'login',
                            'email_verified'    => $fields['email_code'],
                        ));
}

The code after the Validation class is executed. So even when the data is not valid it still adds a new user to the database.
The test I am doing is with empty inputs.
Here are the rules:
protected $_rules = array(
    'username' => array(
        'not_empty' => NULL,
        'min_length' => array(4),
        'max_length' => array(32),
        'regex' => array('/^[-\pL\pN_.]++$/uD'),
    ),
    'password' => array(
        'not_empty' => NULL,
        'min_length' => array(8),
        'max_length' => array(42),
    ),
    'password_confirm' => array(
        'matches' => array('password'),
    ),
    'email' => array(
        'not_empty' => NULL,
        'min_length' => array(4),
        'max_length' => array(127),
        'validate::email' => NULL,
    ),
);

Thanks again in advance for any help.
Answer: The way I setup the rules was wrong and the way I setup the Validation custom rules. Here is the code that resolved the problem:
protected $_rules = array(
    'username' => array(
        array('not_empty'),
        array('min_length', array(4)),
        array('max_length', array(32)),
        array('regex', array('/^[-\pL\pN_.]++$/uD')),
    ),
    'password' => array(
        array('not_empty'),
        array('min_length', array(8)),
        array('max_length', array(42)),
    ),
    'password_confirm' => array(
        array('matches', array(':validation', ':field', 'password')),
    ),
    'email' => array(
        array('not_empty'),
        array('min_length', array(4)),
        array('max_length', array(127)),
        array('email'),
    ),
);

Validation:
$validation = Validation::factory($fields)
        ->rules('username', $this->_rules['username'])
        ->rule('username', array($this, 'username_available'), array(':validation', ':field'))
        ->rules('email', $this->_rules['email'])
        ->rule('email', array($this, 'email_available'), array(':validation', ':field'))
        ->rules('password', $this->_rules['password'])
        ->rules('password_confirm', $this->_rules['password_confirm'])
        ->errors('register/user');
        //->labels($_labels);

    if (Kohana::config('useradmin')->activation_code) {
        $validation->rule('activation_code', array($this, 'check_activation_code'), array(':validation', ':field'));
    }

    if(!$validation->check())
    {
        throw new Validation_Exception($validation, __('Your registering information is not valid.'));
    }

Thank you all for your support!
Answer: There's this thing called an if-else you could use... ;)
Your idea about how the try-catch works is correct: When an exception is thrown inside the try-block, all the remaining code in it is skipped, and it jumps directly into the catch-block.
Most likely the register function is simply not throwing an exception like you assumed, which would be the reason your code is not doing what you think it should.
Comment: LOL Dont' worry I though about if-else. But here is my problem. I need to make sure the content in the form is valid. And I am not sure how to know how it was because I though it would throw an error and skip the other code... I think this is more a Kohana problem...
Comment: I added some code to give you a better idea of what is going on.
Comment: I'm afraid I've never used Kohana so I can't really help with it. Perhaps there's inforomation on how to handle this case in Kohana's docs?
Comment: It seems to me that the Exception is not sent... I am trying to figure out why... There is something that I am missing but I just can't put the finger on it. Thanks anyways for your time and help.
Answer: In this case, the Kohana Auth class dons't have the method register() as default.
I have implemented this method to use in a specific case, with AmfPHP gateway for Kohana Useradmin module.
The right way is to use the model method to add user and it roles, you will get a throw if the array with fields isn't valid.
You can get the result from Auth->instance()->register() like:
    if(! Auth::instance()->register( $_POST )) throw new Validation_Exception(...);

Try or the best way is to change the Auth->instance()->register($_POST) to:
    $user->create_user($_POST, array(
        'username',
        'password',
        'email',
    ));
    // Add the login role to the user (add a row to the db)
    $login_role = new Model_Role(array('name' =>'login'));
    $user->add('roles', $login_role);

It will make your try catch work as needed for Kohana_Validation exception.
To finish, here is the code from register method, it could help you:
/**
 * Register a single user
 * Method to register new user by Useradmin Auth module, when you set the
 * fields, be sure they must respect the driver rules
 *
 * @param array $fields An array witch contains the fields to be populate
 * @returnboolean Operation final status
 * @see Useradmin_Driver_iAuth::register()
 */
public function register($fields)
{
    if( ! is_object($fields) )
    {
        // Load the user
        $user = ORM::factory('user');
    }
    else
    {
        // Check for instanced model
        if( $fields instanceof Model_User )
        {
            $user = $fields;
        }
        else
        {
            throw new Kohana_Exception('Invalid user fields.');
        }
    }
    try
    {
        $user->create_user($fields, array(
            'username',
            'password',
            'email',
        ));
        // Add the login role to the user (add a row to the db)
        $login_role = new Model_Role(array('name' =>'login'));
        $user->add('roles', $login_role);
    }
    catch (ORM_Validation_Exception $e)
    {
        throw $e;
        return FALSE;
    }
    return TRUE;
}

Comment: Even when I put: $model_user->create_user($_POST); directly in the controller it still continues the execution... When it should jump to catch. Here the model source code: https://github.com/jnbdz/Kohana-Cassandra/blob/master/classes/model/auth/user.php
Comment: I look in the my Cassandra DB and I can see tones of new users added but without any values for the columns... So it seems the Validation class is not throwing an Exception because if it did it wouldn't have added all those "none-users". So I think the problem is with the Model itself and with Validation... Can you look at the Model_User and tell me what is causing this issue? Thanks in advance.
Comment: Also I tried to add $_labels in ->labels(...); in the Validation but I get a error saying that $_labels doesn't exists. But at the top you have that variable being given a value... It does not make any sense.


How to get the javascript file (JS) path which is stored in application bundle to html file which is there in document directory

Question: I have one .js file named final.js which I copied as bundle resource I have a requirement like the html document which reads this js file should download at runtime and store it in documents directory. But the js file is not able to read by the html when I loaded it in webview, because of the path of .js file.

I tried with the solution like below, but not worked.

And finally I tried to copy the hardcoded path of application bundle like below, now it worked. Finally I come to know that the path is not proper.
> `

Can any one tell me that how a html file which is stored in documents directory can read a .js file which is stored in main bundle with the correct path instead of hardcoded like above.
Answer: The simple solution will be copying the final.js file to documents directory.
Copy the js file from bundle to the document directory (where the html page is located) and set the path as:

Comment: thanks for reply, that I already done. But my one more requirement is final.js file should don't disclose to outside app. So I need to put it in bundle only.
Comment: @KarthikMitta: AFAIK , If you are not enabled the iTunes File Sharing option, o one can see the files inside the document directory.
Comment: Please explore about Ifunbox software, that can expose every thing even bundle resource files also, but my intention is atleast I can make that file safe from the people don't know about IFunbox.For IFunbox also, if deveice is locked with pin then no one can extract anything.
Comment: you are most welcome. please comment here If you get some solution for my question at any time....
Comment: @KarthikMitta: Sure, I'll do that. Just one thought why can't you use the delegates for copying the JS file. When the application become active copy the JS file, when it terminates or go to background delete that file. I know this is not a good solution.


Convert OpenSSL key to CryptoAPI


Django 1.9.3 - How to pass HTML template to index template

Question: So, I have the index template and in there I have a table that uses Django template language to create a table (using for).
How do I pass the same table (even with Django templating code) to the index template using AJAX? I already added the AJAX portion and it works, but the DJango code is not interpreted and the table is not constructed.
Basically, I would like to:

Separate individual DOM components in "templates" so via AJAX I push to the main (index) template as needed. Please keep in mind that these "templates" should contain Django code like {% for item in data %}.

For instance:
From the view:
def getDetails(request):
 var = "{% if 10 > 5 %}
TRUE
{% endif %}"
 return HttpResponse(
            json.dumps(var),
            content_type="application/json"
        )

index.html:
function getDetails() {
    $.ajax({
        url : "getDetails/",
        type : "POST",
        data : { getDetails : $('#postValue').val() },

        success : function(json) {
            $('#postValue').val('');
            $("#tableDetails").html(json)

What the browser displays:
{% if 10 > 5 %}
TRUE
{% endif %}

Comment: You'll need to give a bit more detail. Why can't you render the template fragment in the view that responds to the Ajax call? Why don't you want to pass any context there?
Comment: I can pass the context containing the HTML table. The problem is that to create the table I am using the template language (since it is pretty simple) when the index template receives the table, it renders everything, including {% for items in collection %} for instance. So the server is not interpreting the Python code.
Comment: But that didn't answer my question: why can't you render the template in the Ajax view, like you would with any other view? Maybe you should show the full code of that view.
Comment: I actually did. I can do it, but it does include the {{ }} tags.
Comment: I edited the post for more details.
Answer: The problem is that this code:
def getDetails(request):
  var = "{% if 10 > 5 %}
TRUE
{% endif %}"
  return HttpResponse(
    json.dumps(var),
    content_type="application/json"
  )

literally just puts that template code into a string and sends it as a JSON object. At no point does the template code get converted to a HTML string.
From your comments, you imply that the server doesn't interpret template code, but this isn't correct! Django's default views most certainly do get involved.
You can do this interpretation yourself using the Template class.
Try the following code:
from django.template import Context, Template
template = Template("{% if 10 > 5 %}
{{ value }}
{% endif %}")

def getDetails(request):
  context = Context({"value": "TRUE"})
  output = template.render(context)
  return HttpResponse(
    json.dumps(output),
    content_type="application/json"
  )

The above example, adapted from the Django 1.9 documentation, demonstrates programmatically using a Template, as well as supplying additional information using a Context object.

Perhaps a better alternative is to leave your template code in a partial template file somewhere. For example, let's say you've created table.html containing the following template code:

{% for item in items %}

{{ item }}

{% endfor %}

Then you can load and render it as follows:
from django.template.loader import render_to_string

def getDetails(request):
  table_rows = ['item 1', 'item 2', 'item 3']
  output = render_to_string("table.html", {"items": table_rows})
  return HttpResponse(
    json.dumps(output),
    content_type="application/json"
  )

This invocation of render_to_string will load template code from table.html, and dynamically create a context using the supplied dict. In this case, the items entry in the Context is set to an array so that the {% for %} tag can loop through it.


Proximity scoring of two strings with different lengths (implementing double summation in R)

Question: I'm trying to implement the following equation in R, and I'm having trouble doing so.
double summation equation
My current approach is the following, but I fear it is not correct because the same score is obtained with the perfect match (sorry for the lengthy, unsophisticated code: I'm very new):
query = "acut myeloid leukemia"
document1 = "acut myeloid leukemia normal karyotyp"
document2 = "acut myeloid leukemia"
document3 = "acut normal karyotyp"

Q <- unlist(strsplit(query, " "))
d1 <- unlist(strsplit(document1, " "))
d2 <- unlist(strsplit(document2, " "))
d3 <- unlist(strsplit(document3, " "))

y <- adist(d1,Q)
double_summation1 = 0
for (i in 1:nrow(y-1)) {
    for (j in 1:ncol(y-1)) {
    double_summation1 = double_summation1 + abs(i-j)
    }
}
double_summation1
scatter <- sum(do.call(pmin, lapply(1:nrow(y), function(x)y[x,])))
dist_d_Q1 <- scatter/double_summation1

y <- adist(d2,Q)
double_summation2 = 0
for (i in 1:nrow(y-1)) {
    for (j in 1:ncol(y-1)) {
    double_summation2 = double_summation2 + abs(i-j)
    }
}
double_summation2
scatter <- sum(do.call(pmin, lapply(1:nrow(y), function(x)y[x,])))
dist_d_Q2 <- scatter/double_summation2

y <- adist(d3,Q)
double_summation3 = 0
for (i in 1:nrow(y-1)) {
    for (j in 1:ncol(y-1)) {
    double_summation3 = double_summation3 + abs(i-j)
    }
}
double_summation3
scatter <- sum(do.call(pmin, lapply(1:nrow(y), function(x)y[x,])))
dist_d_Q3 <- scatter/double_summation3

c(dist_d_Q1, dist_d_Q2, dist_d_Q3)

[1] 23
[1] 8
[1] 8
[1] 0.00 0.00 1.75

I realize there are easy ways to do distance measures, such as the stringdist package. But, my goal is to implement the published equation approach to have as a baseline method.  Thank you for your time!
Comment: What is `dat`?.
Comment: The code was updated and 'dat' replaced with 'y' the matrix.
Comment: why is your `y <- adist(d1,Q)`? should not it equal to # words common to both d1 and Q? `adist` is character mismatched based distance and not distance between words. I think it should be `y<-length(intersect(d1, Q))`
Answer: Since you need to compute min_dist and actual_dist multiple times, you should write them as functions. Also, have your code as close as possible to the algorithm. Something like the following should work:
min_dist <- function(d, Q) {
  W <- intersect(d,Q)
  n <- length(W)
  sum(sapply(0:(n-1), function(i) sapply(0:(n-1), function(j) abs(i-j))))
}

current_dist <- function(d, Q) {
  W <- intersect(d,Q)
  pos <- sapply(W, function(x)which(Q==x))
  n <- length(pos)
  sum(sapply(1:n, function(i) sapply(1:n, function(j) abs(pos[i]-pos[j]))))
}

dist_d1_Q <- min_dist(d1, Q) / current_dist(d1, Q)
dist_d2_Q <- min_dist(d2, Q) / current_dist(d2, Q)
dist_d3_Q <- min_dist(d3, Q) / current_dist(d3, Q)

c(dist_d1_Q, dist_d2_Q, dist_d3_Q)
# [1]   1   1 NaN


Unable to install mysql connector for Python 3

Question: In Python 2.X I used MySQLdb module. But recently I've started to port my application to Python 3.X and now indeed this module is no longer working. This is what I tried to do:
$ pip3 install MySQLdb
$ pip3 install PyMySQL
$ pip3 install mysql-connector-python

But none of these commands (taken from different stackoverflow threads) works. So I need some help.
Comment: What doesn't work?? Try running as root. Try the pip module directly from python: `sudo python3 -m pip install PyMySQL` (This is a pure python driver for mysql - should be compatible with MySQLdb)
Answer: try the following code for installing sql connector for python3
pip install --allow-external mysql-connector-python mysql-connector-python
it worked for me...
Comment: I get this error on python3.4 "DEPRECATION: --allow-external has been deprecated and will be removed in the future. Due to changes in the repository protocol, it no longer has any effect."
Comment: Something has been installed. But how do you use it in code? What is the name of the module and where you see the api of the module?


Why does $x^n = \left[(x-1)\sum\limits_{k=0}^{n-1}x^k\right]+1$?

Question: I was curious about the formula for the difference between a number powered by a certain number and the sum of the number powered from 0 to the number - 1. I found this formula but I'm not sure if this is correct, and if it was correct, I couldn't prove it in a "proper" way. Can someone here show me the proof of this formula because I'm really curious about it?
$$x^n = \left[(x-1)\sum\limits_{k=0}^{n-1}x^k\right]+1$$
Comment: See https://en.wikipedia.org/wiki/Geometric_progression#Related_formulas
Comment: You are asking why $99999+1 = 100000$?
Comment: The sum $(x-1)\sum\limits_{k=0}^{n-1}x^k = \sum\limits_{k=0}^{n-1}(x^{k+1} - x^k)$ is a [telescoping sum](https://en.wikipedia.org/wiki/Telescoping_series). A lot of cancellations appear among the terms and you can read off the end result by replacing the $k$ in $x^{k+1}$ by the largest possible $k$ and the $k$ in $x^k$ by the smallest possible $k$. This gives you $(x-1)\sum\limits_{k=0}^{n-1}x^k = x^{(n-1)+1} - x^0 = x^n - 1$. Look at above wiki entries for more examples of this sort of sums.
Answer: Given a finite series
$$S=\sum_{k=0}^{n-1} x^k=1+x+x^2+\ldots+x^{n-1}$$
We want to find a closed expression for $S$. Note that by multiplying by $x$, we get
$$Sx=x+x^2+x^3+\ldots+x^n$$
Now subtract both eqations and note the massive cancellation,
$$(x-1)S=x^n-1$$
$$(x-1)S+1=x^n$$
$$\left[(x-1)\sum_{k=0}^{n-1} x^k\right]+1=x^n$$
Comment: Thanks, a really brief and clear explanation :)
Answer: Do you know the formula to factor a polynomial in the form of $a^n - b^n$ ?
$x^n - 1^n = x^n - 1 = (x-1)(\sum _{k=0}^{n-1}\:x^k1^{n-1-k}) = (x-1)(\sum _{k=0}^{n-1}\:x^k)$
You take the expression above and you add $+ 1$ to get $x^n$
Comment: Thanks, really helpful
Comment: @edward for proof of $a^n - b^n$ look up https://math.stackexchange.com/a/2031074/
Comment: thanks, its all clear to me now


SUDO Keeps promting for password, when using SSSD with AD

Question: Hi I am trying to setup SSSD to authenticate to AD on RHEL.
I able able to login with my AD user and password and see my groups when I run id. But when I try to use sudo, it just keeps prompting for my password (Sorry, please try again). Any ideas why? I know it is not the sudoers file because when I run  sudo -U myUser -l I see (root) ALL But I can su to root no problem, and I don't get prompted for a password.
My assumption is it has something to do with PAM.
pam.d/system-auth-ac
auth        required      pam_env.so
auth        sufficient    pam_localuser.so
auth        [success=done ignore=ignore default=die] pam_unix.so nullok try_first_pass
auth        requisite     pam_succeed_if.so uid >= 1000 quiet_success
auth        sufficient    pam_sss.so forward_pass
auth        sufficient    pam_krb5.so use_first_pass
auth        required      pam_deny.so

account     required      pam_unix.so broken_shadow
account     sufficient    pam_localuser.so
account     sufficient    pam_succeed_if.so uid < 1000 quiet
account     [default=bad success=ok user_unknown=ignore] pam_sss.so
account     [default=bad success=ok user_unknown=ignore] pam_krb5.so
account     required      pam_permit.so

password    requisite     pam_pwquality.so try_first_pass local_users_only retry=3 authtok_type=
password    sufficient    pam_unix.so shadow nullok try_first_pass use_authtok
password    sufficient    pam_sss.so use_authtok
password    sufficient    pam_krb5.so use_authtok
password    required      pam_deny.so

session     optional      pam_keyinit.so revoke
session     required      pam_limits.so
-session     optional      pam_systemd.so
session     optional      pam_mkhomedir.so umask=0077
session     [success=1 default=ignore] pam_succeed_if.so service in crond quiet use_uid
session     required      pam_unix.so
session     optional      pam_sss.so
session     optional      pam_krb5.so

pam.d/password-auth-ac
auth        required      pam_env.so
auth        [default=1 success=ok] pam_localuser.so
auth        [success=done ignore=ignore default=die] pam_unix.so nullok try_first_pass
auth        requisite     pam_succeed_if.so uid >= 1000 quiet_success
auth        sufficient    pam_sss.so forward_pass
auth        required      pam_deny.so

account     required      pam_unix.so broken_shadow
account     sufficient    pam_localuser.so
account     sufficient    pam_succeed_if.so uid < 1000 quiet
account     [default=bad success=ok user_unknown=ignore] pam_sss.so
account     required      pam_permit.so

password    requisite     pam_pwquality.so try_first_pass local_users_only retry=3 authtok_type=
password    sufficient    pam_unix.so shadow nullok try_first_pass use_authtok
password    sufficient    pam_sss.so use_authtok
password    required      pam_deny.so

session     optional      pam_keyinit.so revoke
session     required      pam_limits.so
-session     optional      pam_systemd.so
session     optional      pam_mkhomedir.so umask=0077
session     [success=1 default=ignore] pam_succeed_if.so service in crond quiet use_uid
session     required      pam_unix.so
session     optional      pam_sss.so

sssd.conf
[sssd]
config_file_version = 2
domains = myDomain
services = nss, pam, pac

[domain/myDomain]
id_provider = ad
access_provider = ad
ad_server = adSer2.ca,adSer1.ca
ad_access_filter = memberOf=CN=IT - Shared Services,OU=Infrastructure,OU=CompanyGrps,DC=company,DC=ca
default_shell = /bin/bash
fallback_homedir = /home/%u
ignore_group_members = true
debug_level = 1

[nss]

[pam]
debug_level = 1
pam_verbosity = 3

[pac]

nsswitch.conf
passwd:     files sss ldap
shadow:     files sss ldap
group:      files sss ldap
#initgroups: files

#hosts:     db files nisplus nis dns
hosts:      files dns

# Example - obey only what nisplus tells us...
#services:   nisplus [NOTFOUND=return] files
#networks:   nisplus [NOTFOUND=return] files
#protocols:  nisplus [NOTFOUND=return] files
#rpc:        nisplus [NOTFOUND=return] files
#ethers:     nisplus [NOTFOUND=return] files
#netmasks:   nisplus [NOTFOUND=return] files

bootparams: nisplus [NOTFOUND=return] files

ethers:     files
netmasks:   files
networks:   files
protocols:  files
rpc:        files
services:   files sss

netgroup:   files sss ldap

publickey:  nisplus

automount:  files sss ldap
aliases:    files nisplus

sudoers
root  ALL=(ALL)   ALL

%it\ -\ shared\ services ALL = (root) ALL

Update
I got it to work by removing kerberos from the PAM configuration, but I am not sure by doing this if I have introduced a security risk.
Comment: any chance you could show /etc/sudoers as well?
Comment: Added the couple line present
Comment: is this a RHEL7 box authenticating with a Windows 2008R2 domain?
Answer: In my experience, I've had to qualify the domain of the group in /etc/sudoers
So my sudoers declaration would look more like this:
%firstname.lastname@example.com ALL = (root) ALL
Since you've got spaces in the group name, something like:
%it\ -\ shared\ firstname.lastname@example.com ALL = (root) ALL
Comment: Tried that, couldn't get it to work. As mentioned, when I run sudo -U myUser -l I can see that I have sudo privileges. So, I do not believe its an issue with sudo. It is an issue with how sudo authenticates.


Will local notification in iOS work even if the app is terminated?

Question: I'm building a reminder-like application that will remind people to take their medication on a scheduled time by firing up a notification to ask the user to open the app for more details about the medication they should take. I'm planning to use local notification instead of push notification, but just wondering if the local notification will still work even if the application is terminated (swipe up in task manager, or in my case I set the app to terminate once home button is clicked).
Comment: What happened when you tried it?
Comment: What do you mean by local notification here?
Answer: Yes, local Notification will work even if your app is terminated. You just need to register a Local Notification with a date on which you want to fire that Notification.
Local Notification will fire on the registered date whether your app is terminated or not.
Answer: Shortest answer : Yes, here is an example how to use local notifications in your app
<code>UILocalNotification* localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:60];
localNotification.alertBody = @"Your alert message";
localNotification.timeZone = [NSTimeZone defaultTimeZone];
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification]
</code>
the fire date property tills the system when you want to fire the notification even if your app is suspended.
Reference : Appcoda!
Comment: If you are copying code from somewhere then give citation or reference!! [http://www.appcoda.com/ios-programming-local-notification-tutorial/](http://www.appcoda.com/ios-programming-local-notification-tutorial/)
Comment: @Lion Thanks for the note, i totally forgot.


Add one class and remove other in javascript

Question: I'm trying to make dark light mode with javascript and local storage but something is not right. Here is the code for toggle icon

and here is js code
const themeButton = document.getElementById('theme-button')
const darkTheme = 'dark-theme'
const iconTheme = 'fa-sun'

const selectedTheme = localStorage.getItem('selected-theme')
const selectedIcon = localStorage.getItem('selected-icon')

const getCurrentTheme = () => document.body.classList.contains(darkTheme) ? 'dark' : 'light'
const getCurrentIcon = () => themeButton.classList.contains(iconTheme) ? 'fa-moon' : 'fa-sun'

if (selectedTheme) {
  document.body.classList[selectedTheme === 'dark' ? 'add' : 'remove'](darkTheme)
  themeButton.classList[selectedIcon === 'fa-moon' ? 'add' : 'remove'](iconTheme)
}

themeButton.addEventListener('click', () => {
    document.body.classList.toggle(darkTheme)
    themeButton.classList.toggle(iconTheme)
    localStorage.setItem('selected-theme', getCurrentTheme())
    localStorage.setItem('selected-icon', getCurrentIcon())
})

When I click icon it adds fa-sun to class attribute and removes it when I click again, but class fa-moon is never removed from class attribute and sun icon is not shown.
Comment: Is your answer in [How can I change an element's class with JavaScript?](https://stackoverflow.com/a/196038/13969786)?
Comment: No, it's not...question is where is the mistake in my code above
Comment: https://developer.mozilla.org/en-US/docs/Web/API/DOMTokenList/replace
Comment: why `darkTheme = 'dark-theme'` and not `darkTheme = 'fa-moon'` ?
Comment: https://jsfiddle.net/506de9gv/
Comment: @MisterJojo because adding class dark-theme to body
Comment: @DimitrisMaragkos I changed your code little bit and finaly manage to fix it...problem solved, thank you all
Answer: Here is how I fixed it...first I changed icon in html code to this

and then changed js like this
const themeButton = document.getElementById('theme-button');
const darkTheme = 'dark-theme';
const darkIcon = 'fa-sun';
const lightIcon = 'fa-moon';

const selectedTheme = localStorage.getItem('selected-theme')
const selectedIcon = localStorage.getItem('selected-icon')

const getCurrentTheme = () => document.body.classList.contains(darkTheme) ? 'dark' : 'light';
const getCurrentIcon = () => themeButton.classList.contains(lightIcon) ? lightIcon : darkIcon;

document.body.classList.add(darkTheme);
themeButton.classList.add(selectedTheme === 'dark' ? lightIcon : darkIcon);

themeButton.addEventListener('click', () => {

  document.body.classList.toggle(darkTheme);
  themeButton.classList.toggle(darkIcon);
  themeButton.classList.toggle(lightIcon);

  localStorage.setItem('selected-theme', getCurrentTheme());
  localStorage.setItem('selected-icon', getCurrentIcon());
});

and now it's working like I wanted-when dark mode is on there is a sun icon and when clicked on sun lite mode is on and moon icon showed.
Comment: I wouldn't store both `selected-theme` and `selected-icon` in `localStorage`. Just theme is enough. You can figure out the icon based on the selected theme.


How to interpret + and - precisions and recalls?

Question: I understand the general calculation and concept of precision and recall. But when I am trying to predict people's ethnicity using some feature, say for example, predicting a binary class Chinese vs non-Chinese. I get a pair of precisions and a pair of recalls from python.
For example:
<code>                     (Gold standard)
                   Chinese  non-Chinese
 (Predicted) Chinese    A         B
         non-Chinese    C         D
</code>
Results
<code>Accuracy    0.9967
Precision + 0.4808
Precision - 0.999
Recall +    0.7095
Recall -    0.9976
</code>
I don't understand what the positive and negative classifications mean?
Answer: Precision and recall both examine your system's performance on a specific class--typically the positive one. For example, recall can be computed as:
$$Recall = \frac{\textrm{True Positives}}{\textrm{True Positives} + \textrm{False Negatives}}$$Similarly , precision can be calculated as
$$Precision = \frac{\textrm{True Positives}}{\textrm{True Positives + False Positives}}$$
In both cases, only one class--the positive class--shows up in the numerator. Your code appears to be computing precision/recall twice, once for the positive class (Chinese) and once for the negative class (non-Chinese).
If you set Chinese as the positive class, you'll get the following:
$$\begin{align}
Recall_+ &= \frac{A}{A+C}\\
Precision_+ &= \frac{A}{A+B} \\
Recall_- &= \frac{D}{B+D} \\
Precision_- &= \frac{D}{C+D}
\end{align}
$$
This isn't exactly wrong, but it strikes me as a little unusual. Precision and recall are great metrics when you care about identifying one type of something in the middle of a sea of distracting and irrelevant stuff. If you're interested in the system's performance on both classes, another measure (e.g., aROC) might be better.
Comment: Sorry I am still confused about what the + and - means. Say I define "Chinese" as the positive, then the recall + will be A/(A+B), correct? And if I define "non-Chinese" as negative, will the recall - be D/(C+D)? And isn't D/(C+D) just the same as precision +?
Comment: Sorry--I made a few stupid mistakes in the first version (wrote recall where I meant precision). I hope this clears it up.

In general, recall_ is not going to be equal to precision+ or anything like that though....


Variance of a stationary AR(2) model

Question: I have two questions:
1) When one says an ARMA process is 'stationary,' do they mean strongly stationary or weakly stationary?
2) Is there a quick way to find the variance of a stationary AR(2) model $$y_t = \beta_1 y_{t-1} + \beta_2 y_{t-2} + \epsilon_t?$$ The only way I can think of doing this is by multiplying by $y_t$, $y_{t-1}$ and $y_{t-2}$, taking expectations, and solving the Yule-Walker system with 3 equations and 3 unknowns. The trick for AR(1) models, where one takes expectations of both sides, doesn't slide here because you get a $\mathrm{Cov}(y_{t-1}, y_{t-2})$ term.
Comment: Regarding (1), it must depend on the context. An answer claiming otherwise would be careless, IMHO.
Comment: Regarding (2), the variance of the AR(2) model will depend on the first and second order autocovariances. As you say, in order to get its value you will have to solve the Yule-Walker equations; by doing so, I think you will get $Var(y_t)=\frac{(1-\beta_2)\sigma^2_\varepsilon}{(1+\beta_2)[(1-\beta_2)^2-\beta_1^2]}$.
Comment: +1 @RichardHardy Please allow me to add a plug for precisely communicating one's methods, and results!
Answer: Stationarity
Considering your AR(2) process with mean zero i.i.d. noise $\epsilon_t$ of variance $\sigma_\epsilon^2$,
$$
y_t = \beta_1 y_{t-1} + \beta_2 y_{t-2} + \epsilon_t  \,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,(*)
$$
we can rewrite it in terms of the lag operator $L$
$$
(1 - \beta_1 L - \beta_2 L^2)y_t = \epsilon_t
$$
so that we have a new operator
$$
1 - \beta_1 L - \beta_2 L^2
$$
If the above were a polynomial in $L$, let its roots be $z_1^{-1}, z_2^{-1}$.  We call the polynomial the characteristic polynomial, and $z_1, z_2$  its factors.  (Note the factors and roots are inverses of each other, and may be complex.)
It can be shown that the AR(2) is stationary when $|z_1| < 1$ and $|z_2|<1$.  i.e. when all of the following are met:
$$
|\beta_2| < 1 \\
\beta_2 + \beta_1 < 1 \\
\beta_2 - \beta_1 < 1
$$
For details, see this answer.  Or in terms of the more general ARMA(p,q) process, see Introduction to Time Series and Forecasting. Brockwell and Davis. 2016. p 74.
Variance
If the process is stationary, we can write the covariance as a function of increment alone, so let the covariance function $\gamma(k) \doteq E[y_t y_{t+k}]$.  We can find the variance $\gamma(0)$ by squaring and taking the expectation of both sides of equation $(*)$ with the following result
$$
\gamma(0) = \beta_1^2 \gamma(0) + \beta_2^2 \gamma(0) + 2 \beta_1 \beta_2 \gamma(1) + \sigma_\epsilon^2 \,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,(**)
$$
Starting again from equation $(*)$, this time multiply both sides by $y_{t-k}$ and again take the expectation
$$
\gamma(k) = \beta_1 \gamma(k-1) + \beta_2 \gamma(k-2)
$$
Usefully, we now have an expression for covariance, but we just need it to compute $\gamma(1)$.  Since $\gamma(-1) = \gamma(1)$ (examine the definition, note that covariance is not a function of $t$), we can let $k=1$ in the above equation and get
$$
\gamma(1) =  \frac{\beta_1 \gamma(0)}{1-\beta_2}
$$
Substituting into $(**)$, we get the variance
$$
\text{Var}(y_t) = \gamma(0) = \frac{(1-\beta_2)\sigma_\epsilon^2}{(1+\beta_2)(1 - \beta_1 - \beta_2)(1 + \beta_1 - \beta_2)}
$$
As a sanity check, our stationarity conditions on $\beta_1, \beta_2$ described earlier are precisely the conditions which make our expression for $\text{Var}(y_t)$ positive.
The above is essentially a summary and rearrangement of some parts of these notes.
Strong or Weak Stationarity
I have only seen arguments of AR process stationarity in terms of fixed mean and variance, so weak stationarity is implied.  However, if the stationary distribution can be characterized completely in terms of those first and second moments, then we also have strong stationarity.  See A unified view of linear AR(1) models. G.K. Grunwald. 1996.
As an example, if we have an AR(1) process and $\epsilon_t$ is i.i.d. Gaussian, then the process' stationary distribution is also Gaussian.  Since the Gaussian is fully specified by its first two moments, we have strong stationarity in that case.  I am unsure whether or not this also applies to more general AR(p) Gaussian processes, or to AR(p) processes with other kinds of i.i.d. noise.
Comment: I have seen the notes you mention above. However I have not been able to find your last equation from (**)  your $\gamma(1)$ Equation. Could you please help? Thakns
Comment: Can you include more detail @Herman?  I don't understand your question yet.
Comment: Unfortunately there is no room here to show you my computations. I wish I can include a file on this comment.  I cannot get your equation for Var(y_t) doing what you are saying. That is, plugging he expression for $\gamma(1)$ in Equation (**). Thanks
Comment: I did it my own way. I will post my computations.
Answer: I do not have enough reputation to comment, so I'll post it as an answer instead:
The accepted answer can be simplified to:
$$
\sigma = \frac{\sigma_Z^2}{1-\beta_1^2 (\frac{1+\beta_2}{1-\beta_2})-\beta_2^2}
$$
See also:
Prove the Variance of an AR(2) Model
EDIT:
So I re-did the math and it seems the answer of the posted link contains a small mistake. I updated the simplified answer accordingly.
Answer: Stack it, i.e. write as VAR(1) for the vector x(t) = [y(t),y(t-1)]', x(t) = [beta1,beta2;1,0] x(t-1) + [epsilon(t),0]'.  Vectorize the resulting matrix equation and exploit vec(ABC)=(C' kron A) vec(B)
Comment: Welcome to CV, Harald Uhlig. Your answer would be made much more clear by editing it to use [MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) (a LaTeX-like mark-up language). You can get a feel for this by examining a CV question or answer by clicking it's "edit" button (not that you need to actually suggest an edit when doing so! :). You can similarly edit your own answer using the "edit" link at lower left.
Answer: From $X_t = \phi_1 X_{t-1} + \phi_2 X_{t-2} $,
\begin{eqnarray*}
E[ X_t X_{t-k}] &=& \phi_1 E[X_{t-1} X_{t-k}] + \phi_2 E[X_{t-2} X_{t-k}] + E[X_t X_{t-1}]   \\
    \gamma_k &=& \phi_1 \gamma_{k-1} + \phi_2 \gamma_{k-2}  + E[Z_t X_{t-k}]   \quad (*)
    \end{eqnarray*}
Now,
\begin{eqnarray}
    E[Z_t X_{t-k}] = \left \{
    \begin{array}{cc}
    \sigma_Z^2 & \text{if } k = 0 \\
      0  & \text{if    } k=1,2, \cdots
      \end{array}
\right .    (**)
\end{eqnarray}
Then combining (*) with (**) and using the symmetry property
of the autocorrelation function. That is, $\gamma_t = \gamma_{-t}$
\begin{eqnarray}
  \sigma^2 = \gamma_0 &=& \phi_1 \gamma_{1} + \phi_2 \gamma_{2}  +
  \sigma_Z^2   \quad , \quad (****) \\
    \gamma_k &=& \phi_1 \gamma_{k-1} + \phi_2 \gamma_{k-2}   \quad , \quad k=1,2, \cdots.  \quad , \quad (***)
    \end{eqnarray}
We need to find $\gamma_1$ and $\gamma_2$. From ()
\begin{eqnarray}
  \gamma_1 = \phi_1 \gamma_0 + \phi_2 \gamma_{-1} = \phi_1 \gamma_0 + \phi_2 \gamma_1   \\
             \gamma_1 = \frac{\phi_1 \gamma_0}{1 - \phi_2} = \frac{\phi_1 \sigma^2}{1 - \phi_2}
             \end{eqnarray}
From () with $k=2$ we find that
\begin{eqnarray}
\gamma_2 = \phi_1 \gamma_1 + \phi_2 \gamma_0 = \phi_1 \frac{\phi_1 \sigma^2}{1-\phi_2} + \phi_2 \sigma^2 = \sigma^2 \left ( \frac{\phi_1^2 + \phi_2(1 - \phi_2) }{1 - \phi_2}\right )  \quad , \quad  (*****)
  \end{eqnarray}
Then by pluggin this in (****)
$$ \sigma^2 = \phi_1 \left (  \frac{\phi_1 \sigma^2}{1 - \phi_2} \right ) + \phi_2 \sigma^2 \left ( \frac{\phi_1^2 + \phi_2(1 - \phi_2) }{1 - \phi_2}\right ) + \sigma_Z^2$$
That is,
\begin{eqnarray}
  \sigma^2 \left [1 -  \left (  \frac{\phi_1^2}{1 - \phi_2} \right ) -\phi_2 \left ( \frac{\phi_1^2 + \phi_2(1 - \phi_2) }{1 - \phi_2}\right ) \right ] = \sigma_Z^2
  \end{eqnarray}
We simplify the quantity in brackets. That is:
\begin{eqnarray}
  1 -  \left (  \frac{\phi_1^2}{1 - \phi_2} \right ) -\phi_2 \left ( \frac{\phi_1^2 + \phi_2(1 - \phi_2) }{1 - \phi_2}\right ) &=&\frac{1 -\phi_2 - \phi_1^2 - \phi_2 \phi_1^2 - \phi_2^2 + \phi_2^3}{1 - \phi_2}  \\
&=& \frac{(1 - \phi_2^2) - \phi_1^2(1 + \phi_2) + \phi_2(\phi_2^2 -1)}{1 - \phi_2}  \\
&=&  \frac{(1-\phi_2)(1 + \phi_2) - \phi_1^2(1 + \phi_2) - \phi_2(1 -\phi_2)(1 + \phi_2) }{1-\phi_2}  \\
&=& \frac{(1 + \phi_2) (1 - \phi_2 - \phi_1^2 - \phi_2(1 - \phi_2))}{1 - \phi_2} \\
&=& \frac{(1 + \phi_2) (1 - 2 \phi_2 + \phi_2^2 - \phi_1^2)}{1  - \phi_2} \\
&=& \frac{(1 + \phi_2)[( 1 - \phi_2)^2 - \phi_1^2]}{1 - \phi_2} \\
&=& \frac{(1+ \phi_2)( 1 - \phi_2 - \phi_1)(1 - \phi_2 + \phi_1)}{1 - \phi_2}
\end{eqnarray}
We find then that
\begin{eqnarray}
\sigma^2 = \frac{(1 - \phi_2) \sigma_Z^2}{(1+ \phi_2)( 1 - \phi_2 - \phi_1)
  (1 - \phi_2 + \phi_1)}
\end{eqnarray}

Variance of a stationary AR(2) model


Switch from days to hours after a certain time

Question: Goal: Once the time hits two days or less, then it switches to hours instead of days.
Problem: In checking code by changing the date, it still only shows the days left, and not the hours. Am I missing something?
var countDownDate = new Date("Nov 15, 2020 11:59:59").getTime();

var x = setInterval(function() {

  var now = new Date().getTime();

  var distance = countDownDate - now;

  var days = Math.floor(distance / (1000 * 60 * 60 * 24));
  var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));

 if (distance < 2) {
    clearInterval(x);
    document.getElementById("aep-countdown-date").innerHTML = hours + " hours left";
  }

  else if (distance < 0) {
    clearInterval(x);
    document.getElementById("aep-countdown-date").innerHTML = "The time has ended.";
  }

  else  {
      clearInterval(x);
      document.getElementById("aep-countdown-date").innerHTML = days + " days left";
  }
});

Answer: The Date method getTime returns:

the number of milliseconds* since the Unix Epoch.

Your code countDownDate - now returns the number of milliseconds from now until the target date.
However, your comparison distance < 2 is treating distance (which is in ms) as if it were in days.
You probably want
ms in seconds ------------------+
seconds in hour ---------+      |
hours in day ------+     |      |
         days -+   |     |      |
               |   |     |      |
if (distance < 2 * 24 * 3600 * 1000) {
   /* ... */
}

Comment: Thanks for responding! That logic makes sense. However, I'm still getting 0 hours when I change the date to be less than two days out. I'm going to check to see if the hours variable needs to be updated in order to calculate the hours left.
Comment: So, that's a different question; you should create a new question on the site for that
Answer: With help of the previous two responses, I figured it out. I added "2x" to the hours variable and changed the variable to days in the if statements and rid of the setInterval because it wasn't needed (I only need days and hours, not milliseconds and for it to constantly be firing):
var countDownDate = new Date("Nov 15, 2020 11:59:59").getTime();

    $(function() {
        var now = new Date().getTime();

        var distance = countDownDate - now;

        var days = Math.floor(distance / (1000 * 60 * 60 * 24));
        var hours = Math.floor(
            (2 * (distance % (1000 * 60 * 60 * 24))) / (1000 * 60 * 60)
        );

        document.getElementById("aep-countdown-date").innerHTML =
            days + " days left.";

        if (days < 0) {
            document.getElementById("aep-countdown-date").innerHTML = "Time has ended.";
        }

        if (days < 2) {
            document.getElementById("aep-countdown-date").innerHTML =
                hours + " hours left.";
        }
    });


$\mathbb{Q}[i]$ is the smallest subfield of $\mathbb{C}$ that contains the ring $\mathbb Z[i]$

Question: We have that $\mathbb{Z}[i]=\{a+bi,a,b\in \mathbb{Z}\}\subseteq \mathbb{C}$ and $\mathbb{Q}[i]=\{a+bi,a,b\in \mathbb{Q}\}\subseteq \mathbb{C}$, where $\mathbb{Z}$ is a subring of $\mathbb{C}$ and $\mathbb{Q}$ is a subfield of $\mathbb{C}$. I am asked to show that $\mathbb{Q}[i]$ is the smallest subfield of $\mathbb{C}$ that contains the ring $\mathbb Z[i]$.
How could I do that? Do I have to suppose that there is an other field that is smaller than $\mathbb{Q}$?? But how could I get a contradiction??
Comment: $\mathbb{Q}$ does not contain the ring $\mathbb{Z}[i]$.
Answer: Note that any subfield $\Bbb F \subset \Bbb C$ with $Z[i] \subset \Bbb F$ contains $\Bbb Z$, hence contains $\Bbb Q$.  $\Bbb F$ also contains $i$, so it in fact contains every $a + bi \in \Bbb Q[i]$.  This shows that $Q[i] \subset \Bbb F$ for any such  field $\Bbb F$, including $Q[i]$ itself.  Thus $Q[i]$ is the smallest such subfield of $\Bbb C$ with respect the the partial ordering "$\subset$".
Addendum in response to comment of Mary Star, Wednesday 8 October 2014 6:39 PM PST:  We have $\Bbb Z \subset \Bbb F$; but since $\Bbb F \subset \Bbb C$ is a field,
it must also contain $z^{-1}$ for every $0 \ne z \in \Bbb Z$.  Then for every $y \in \Bbb Z$, we have $yz^{-1} \in \Bbb F$ as well.  But the set of all complex numbers of the form $yz^{-1}$, $0 \ne z \in \Bbb Z$, $y \in \Bbb Z$ is clearly the rationals $\Bbb Q$.  Thus $\Bbb Q \subset \Bbb F$.
Hope this helps.  Cheers,
and as always,
Fiat Lux!!!
Comment: I got stuck right now... Could you explain me why when $\mathbb{F}$ contains $\mathbb{Z}$ we conclude that it contains also $\mathbb{Q}$??
Comment: @MaryStar:  I edited my answer in response to your comment; see above.  Cheers!
Answer: The fraction field of an integral domain is the smallest field in which it can embedded. Now the fraction field of $\mathbb{Z}[i]$ clearly is $\mathbb{Q}[i]$, see the above link. Hence $\mathbb{Q}[i]$ is the smallest field containing $\mathbb{Z}[i]$.
Answer: The standard way to show "$X$ is the smallest $Y$ which has property $Z$" is to show that

$X$ is actually a $Y$ which has property $Z$; and
any $Y$ which has property $Z$ must contain $X$.

Here, you already have the first part: $\mathbf{Q}[i]$ is a field which contains $\mathbf{Z}[i]$. You now need to show the second part: any field which contains $\mathbf{Z}[i]$ must contain $\mathbf{Q}[i]$.
Answer: Hint: a field contains $\mathbf{Z}[i]$ if and only if it contains $\mathbf{Z}$ and also contains $i$.
Work one piece at a time rather than trying to use everything at once.


How to apply a function that works with data.frame cells to data.frame columns

Question: This question is the adaptation of a prior question I felt I asked in an unclear way. I am checking whether columns V1 and V2 have common codes by row. Codes are separated by a forward slash "/". The function below should take one cell from V1 and one cell from V2 on the same row and should transform them into vectors. Each element of a vector is one code. Then the function should check whether the two vectors obtained have elements in common. These elements initially are 4-digit codes. If there is any 4-digit code that matches between the two vectors, the function should return 4. If there are no elements in common, the function should reduce the number of digits of each code and then check again. Every time that the function reduces the number of digits, it also reduces the score it returns at the end. I would like the value returned by the function to be written in a column of my choice.
This is my starting condition
structure(list(ID = c(2630611040, 2696102020, 2696526020), V1 = c("7371/3728",
"2834/2833/2836/5122/8731", "3533/3541/3545/5084"), V2 = c("7379",
"3841", "3533/3532/3531/1389/8711")), .Names = c("ID", "V1",
"V2"), class = "data.frame", row.names = c(NA, 3L))

         ID                       V1                       V2
1 2630611040                7371/3728                     7379
2 2696102020 2834/2833/2836/5122/8731                     3841
3 2696526020      3533/3541/3545/5084 3533/3532/3531/1389/8711

And I would like to get this
          ID                       V1                       V2   V3
1 2630611040                7371/3728                     7379   3
2 2696102020 2834/2833/2836/5122/8731                     3841   0
3 2696526020      3533/3541/3545/5084 3533/3532/3531/1389/8711   4

My function is this
coderelat<-function(a, b){

a<-unique(as.integer(unlist(str_split(a, "/")))) #Transforming cells into vectors of codes
b<-unique(as.integer(unlist(str_split(b, "/"))))

a<-a[!is.na(a)]
b<-b[!is.na(b)]

if (length(a)==0 | length(b)==0) { # Check that both cells are not empty

  ir=NA
  return(ir)

  } else {

for (i in 3:1){

    diff<-intersect(a, b) # See how many products the shops have in common

            if (length(diff)!=0) { #As you find a commonality, give ir the corresponding scoring

              ir=i+1
              break

            } else if (i==1 & length(diff)==0) { #If in the last cycle, there is still no commonality put ir=0

              ir=0
              break

            } else { # If there is no commonality and you are not in the last cycle, reduce the nr. of digits and re-check commonality again

              a<- unique(as.integer(substr(as.character(a), 1, i)))
              b<- unique(as.integer(substr(as.character(b), 1, i)))

        }

    }
  }
return(ir)
}

The function works when I manually supply single cells. But it doesn't work when I write soemthing like this:
df$V4<-coderelat(df$V1, df$V2)

I really appreciate any help because I don't know anymore how to make this work.
Many thanks in advance.
Riccardo
Comment: Providing your data using `dput(...)` is very helpful (+1).
Answer: Here's a solution using data.tables.
get.match <-function(a,b) {
  A <- unique(strsplit(a,"/",fixed=TRUE)[[1]])
  B <- unique(strsplit(b,"/",fixed=TRUE)[[1]])
  for (i in 4:1) if(length(intersect(substr(A,1,i),substr(B,1,i)))>0) return(i)
  return(0L)
}
library(data.table)
setDT(df)[,V3:=get.match(V1,V2),by=ID]
df
#            ID                       V1                       V2 V3
# 1: 2630611040                7371/3728                     7379  3
# 2: 2696102020 2834/2833/2836/5122/8731                     3841  0
# 3: 2696526020      3533/3541/3545/5084 3533/3532/3531/1389/8711  4

Comment: It's a great answer! Many thanks, really. I have two questions to clarify your solution. First, could you please explain the [[1]] at the end of the 2nd and 3rd line of get.match? Second, what does the function do in case, say A=NA? Many thanks again!
Comment: `strsplit(...)` creates a list of character vesctors. In your case that list has only one element, so we extract is using `[[1]]`.