save a Google Chart server-side

I made a JS script that pulls data from a Postgres database and visualizes them as a bunch of beautiful Google Charts. That works fine, but it is very slow and sometimes the web page just times out.

To remedy, I was thinking of creating the charts as PNG/GIF/SVG/Whatever, and use a cron job to refresh the charts at specific intervals. That would sacrifice interactivity (which is not very important in this instance) for speed. However, a google search does not provide a clear path for creating Google charts with PHP. Any suggestions?

Here is my JS script:

            google.setOnLoadCallback(drawManyCharts);

        function drawManyCharts()
        //parameters are: timeUnit, target div, abscissa bins, MultiplicationFactor, Graphtype, SensorString
        {drawAllCharts("minutes", "GoogleChart_div", 500, 0.01, "Linechart", "Temperature");
        drawAllCharts("hours", "GoogleChart2_div", 400, 0.01, "Linechart", "Temperature");
        drawAllCharts("days", "GoogleChart3_div", 48, 0.01, "Linechart", "Temperature");
        drawAllCharts("weeks", "GoogleChart4_div", 48, 0.01, "Linechart", "Temperature");
        drawAllCharts("hours", "GoogleChartPressure_div", 48, 0.01, "Linechart", "Pressure");
        }

        function drawAllCharts(TimeUnit, containerChart, NoAbscissaBins, MultiplicationFactor, Graphtype, SensorString)
        {

        //    var  SensorString="Temperature";
              var  TableType="integer";
        //    var  NoAbscissaBins=12;
              var  DataTableName="dataMasterTable";
        //    var  TimeUnit="days";
              var  TimeStart="test";
        //    var  Graphtype="Linechart";
              var  graphtitle = "Heizungskeller";
              var  OrdinateLabel = "Temperature (Celsius 100x)"
              var  maxViewWindow= 8000;
              var  minViewWindow= 0;

              var GoogleArray = $.ajax({
                url: "/php/PrepareGoogleDataTable.php" +"?"+
                            "SensorString="+SensorString + "&"+
                            "TableType=" + TableType +"&"+
                            "NoAbscissaBins=" + NoAbscissaBins + "&"+
                            "MultiplicationFactor=" + MultiplicationFactor + "&"+
                            "DataTableName=" + DataTableName +"&"+
                            "TimeUnit=" + TimeUnit +"&"+
                            "TimeStart=" + TimeStart,
                //dataType:"json",
                async: false
                }).responseText;
                console.log(GoogleArray);
                GoogleArray = JSON.parse(GoogleArray);
                eval(GoogleArray.GoogleAddColumns);
                eval(GoogleArray.GoogleAddRows);

        //create dynamic dataview for charts
        //columns as specified by TableType
        switch (TableType)
        {
        case "boolean":
            eval(GoogleArray.GoogleVisualizeColumnCount)  ;
        break;

        case "integer" :
            eval(GoogleArray.GoogleVisualizeColumnsMinStdevStdevMax)  ;
            eval(GoogleArray.GoogleVisualizeColumnsAvg)  ;
        break;

        case "float" :
            eval(GoogleArray.GoogleVisualizeColumnsMinStdevStdevMax)  ;
            eval(GoogleArray.GoogleVisualizeColumnsAvg)  ;
        break;

        case "string" :
        break;

        }

        switch (Graphtype)
        {
        case "Candlestick":
         var optionsCandlestick = {
            width: '100%',
            height: 480,
            bar:{groupWidth: '90%'},
            vAxis: {minValue: 0,
                    baseline: 0,
                    textStyle: {color: 'blue',
                                fontSize: 10},
                    viewWindowMode: 'explicit',
                    viewWindow: {max: maxViewWindow,
                                min: minViewWindow
                                }
                    },
            hAxis: {textStyle:
                        {color: 'blue',
                        fontSize: 10},
                    },
            pointSize: 5,
            title: graphtitle
            };

        var wrapper = new google.visualization.ChartWrapper(
             {chartType: 'CandlestickChart',
              dataTable: dataViewMinStdevStdevMax,
                options: optionsCandlestick,
                containerId: containerChart});
                wrapper.draw();

        break;

        case "StackedColumn":

        var optionsColumnchart = {
            chartArea: {width: '80%', height: '70%'},
            //legend: {position: 'in'},
            //titlePosition: 'in',
            axisTitlesPosition: 'in',
            hAxis: {textPosition: 'in'},
            vAxis: {textPosition: 'in'},
            width: '100%',
            height: 520,
            isStacked: true,
            pointSize: 3,
            fontSize: 10,
            backgroundColor: 'transparent',
            bar:{groupWidth: '90%'},
            hAxis:{slantedTextAngle: 90},
            legend:{position: 'in', textStyle: {color: 'blue', fontSize: 12}},
            title: graphtitle
            };
        var wrapper = new google.visualization.ChartWrapper(
             {chartType: 'ColumnChart',
              dataTable: dataViewCount,
                options: optionsColumnchart,
                containerId: containerChart});
                wrapper.draw();
        break;

        case "Linechart":
            //these are the customizable options from google
            var optionsLinechart = {
                        chartArea: {width: '80%', height: '70%'},
                        //legend: {position: 'in'},
                        width: 1000,
                        height: 480,
                        pointSize: 0,
                        title: graphtitle,
                        vAxis: {title: OrdinateLabel}
        };

            var wrapper = new google.visualization.ChartWrapper(
             {chartType: 'LineChart',
              dataTable: dataViewAvg,
                options: optionsLinechart,
                containerId: containerChart});
                wrapper.draw();
        break;

        }

        }
        </script>

and here is the PHP script that takes Postgres data and converts them into a Google Chart-digestible format:

    <?php
    if(isset($_GET['SensorString']) &&
        (!empty($_GET['SensorString'])) &&
        (!empty($_GET['TableType'])) &&
        (!empty($_GET['TimeUnit'])) &&
        (!empty($_GET['NoAbscissaBins'])) &&
        (!empty($_GET['DataTableName'])) &&
        (!empty($_GET['MultiplicationFactor'])) &&
        (!empty($_GET['TimeStart'])))

        {$SensorString = str_replace ( "*", "%", $_GET['SensorString']); // string to fill "WHERE" condition
         $TableType = $_GET['TableType']; // boolean/integer/float/string
         $TimeUnit = $_GET['TimeUnit']; //hours/days/weeks/months/years
         $NoAbscissaBins = $_GET['NoAbscissaBins']; //number of time units to be displayed on the abscissa
         $DataTableName = $_GET['DataTableName']; //number of time units to be displayed on the abscissa
         $TimeStart = $_GET['TimeStart']; //should not necessarily be used

         }
    else
        {// assume Bewegungsmelder, boolean, hours, 12 bins
        $SensorString = "OutsideTemp";
        $TableType = "float";
        $TimeUnit = "days";
        $TimeStart = -12;
        $NoAbscissaBins = 30;
        $DataTableName = "dataMasterTable";
        }

    $RedirectEchoToFile = false;

    $DataCollectionArray = DataCollectionCrossTab($SensorString, $TableType, $TimeUnit, $NoAbscissaBins, $TimeStart, $DataTableName);
    //echo  "GoogleDataRow:  ". $DataCollectionArray['GoogleDataRow'] ;
    $GoogleArray = PrepareGoogleChart($DataCollectionArray);

    /*  $GoogleArray has the following keys:
    /   [0] => GoogleAddColumns
    /   [1] => GoogleAddRows
    /   [2] => GoogleVisualizeColumnCount
    /   [3] => GoogleVisualizeColumnsAvg
    /   [4] => GoogleVisualizeColumnsMinStdevStdevMax
    /   [5] => MainCrosstabSelectQuery
    */

    echo json_encode($GoogleArray);

    //---------------------------------------------------

    Function PrepareGoogleChart($DataCollectionArray)
    {
    // var GoogleAddColumns adds columns to DataTable

    $TimeUnit = "hours"; // (can be "hours", "days", "months", "years" )
    $GoogleAddColumns = "";

    // var GoogleVisualizeColumnsAll renders DataView1 view of DataTable
    // var VisualizeFirstColumn sets the first column, and renders "hours" (can be changed to days etc.)
    $VisualizeFirstColumn = ".setColumns([
                            {calc: function(data, row)
                            {return data.getFormattedValue(row, "
                            . ColumnLabel($TimeUnit). "); },
                            type:'string'}";

    //set up dataView1, which is essentially useless
    $GoogleVisualizeColumnsAll =
        "var dataView1 = new google.visualization.DataView(".$DataCollectionArray['DataTableName'].");".chr(13)
        ."dataView1".$VisualizeFirstColumn;

    //set up dataViewCount, which is good to count events from IpsLoggingBoolean and feed a column chart
    $GoogleVisualizeColumnCount =
        "var dataViewCount = new google.visualization.DataView(".$DataCollectionArray['DataTableName'].");"
        .chr(13)."dataViewCount".$VisualizeFirstColumn;

    //set up dataViewAvg, which visualizes only the averages and is good for line charts
    $GoogleVisualizeAvg =
        "var dataViewAvg =
            new google.visualization.DataView(".$DataCollectionArray['DataTableName'].");".chr(13).
            "dataViewAvg"
            .".setColumns([ {calc: function(data, row)
                            {return data.getFormattedValue(row, "
                            . ColumnLabel($TimeUnit). "); },
                            type:'string'}";

    //set up dataViewMinStdevStdevMax, which can feed a candlestick chart
    $GoogleVisualizeColumnsMinStdevStdevMax =
        "var dataViewMinStdevStdevMax =
            new google.visualization.DataView(".$DataCollectionArray['DataTableName'].");".chr(13)
            ."dataViewMinStdevStdevMax"
            .".setColumns([ {calc: function(data, row)
                            {return data.getFormattedValue(row, "
                            . ColumnLabel($TimeUnit). "); },
                            type:'string'}";

    $GoogleVisualizeScattergram =
        "var dataViewScattergram = new google.visualization.DataView(".$DataCollectionArray['DataTableName'].");"
        .chr(13)."dataViewScattergram.setColumns([";

    //create strings for Google DataTable/DataView1 columns definition
    $GoogleAddColumns =
          "var ". $DataCollectionArray['DataTableName']. "= new google.visualization.DataTable();".chr(13).
          $DataCollectionArray['DataTableName'].".addColumn('string', 'hoursIndex');".chr(13).
          $DataCollectionArray['DataTableName'].".addColumn('string', 'hours');".chr(13).
          $DataCollectionArray['DataTableName'].".addColumn('string', 'PlaceHolder1');".chr(13).
          $DataCollectionArray['DataTableName'].".addColumn('string', 'PlaceHolder2');".chr(13).
          $DataCollectionArray['DataTableName'].".addColumn('string', 'PlaceHolder3'); ";

    for ($varIndex=0; $varIndex < ($DataCollectionArray['NumberOfColumns']-5); $varIndex++)
      {

      Switch ($DataCollectionArray['TableType'])
        {
        case "boolean":
          $GoogleAddColumns .=
          $DataCollectionArray['DataTableName'].".addColumn('number', ".$DataCollectionArray['CategoryArray'][$varIndex]. ", 'count$varIndex'); ";
        break;

        case "integer":
            $GoogleAddColumns .=
        $DataCollectionArray['DataTableName'].".addColumn('number', ".$DataCollectionArray['CategoryArray'][$varIndex]. " +'avg'); ".chr(13).
        $DataCollectionArray['DataTableName'].".addColumn('number', ".$DataCollectionArray['CategoryArray'][$varIndex]. " +'stddev+'); ".chr(13).
        $DataCollectionArray['DataTableName'].".addColumn('number', ".$DataCollectionArray['CategoryArray'][$varIndex]. " +'stddev-');  ".   chr(13).
        $DataCollectionArray['DataTableName'].".addColumn('number', ".$DataCollectionArray['CategoryArray'][$varIndex]. " +'max');  " .chr(13).
        $DataCollectionArray['DataTableName'].".addColumn('number', ".$DataCollectionArray['CategoryArray'][$varIndex]. " +'min'); " .chr(13);
        break;

        case "float":
            $GoogleAddColumns .=
        $DataCollectionArray['DataTableName'].".addColumn('number', ".$DataCollectionArray['CategoryArray'][$varIndex]. " +'avg'); ".chr(13).
        $DataCollectionArray['DataTableName'].".addColumn('number', ".$DataCollectionArray['CategoryArray'][$varIndex]. " +'stddev+'); ".chr(13).
        $DataCollectionArray['DataTableName'].".addColumn('number', ".$DataCollectionArray['CategoryArray'][$varIndex]. " +'stddev-');  ".   chr(13).
        $DataCollectionArray['DataTableName'].".addColumn('number', ".$DataCollectionArray['CategoryArray'][$varIndex]. " +'max');  " .chr(13).
        $DataCollectionArray['DataTableName'].".addColumn('number', ".$DataCollectionArray['CategoryArray'][$varIndex]. " +'min'); " .chr(13);
        break;

        case "string":
        //no visualization in case of strings, but a "tableChart" could be generated if need be.
        break;
        }

    $GoogleVisualizeColumnsAll .=
        ", ". strval(($varIndex+1)*4+1).", ".
        strval(($varIndex+1)*4+2).", ".
        strval(($varIndex+1)*4+3).", ".
        strval(($varIndex+1)*4+4);

    $GoogleVisualizeColumnCount .=
        ", ". strval(($varIndex+1)+4);

    $GoogleVisualizeAvg .=
        ", ". strval(($varIndex+1)*5+0);

    $GoogleVisualizeColumnsMinStdevStdevMax .=
        ", ". strval(($varIndex+1)*5+1).
        ", ". strval(($varIndex+1)*5+2).
        ", ". strval(($varIndex+1)*5+3).
        ", ". strval(($varIndex+1)*5+4);

    $GoogleVisualizeScattergram .=  strval(($varIndex+1)*4+2).", ";
      }

    //echo "Tabletype: ". $DataCollectionArray['TableType'].chr(13)."<br>"."<br>";
    //echo "GoogleAddColumns:   ". $GoogleAddColumns.chr(13)."<br>"."<br>";

      $GoogleVisualizeColumnsAll .=             "]);".chr(13);
      $GoogleVisualizeColumnCount .=            "]);".chr(13);
      $GoogleVisualizeAvg .=                    "]);".chr(13);
      $GoogleVisualizeColumnsMinStdevStdevMax.= "]);".chr(13);
      $GoogleVisualizeScattergram = substr($GoogleVisualizeScattergram, 0, -2) . "]);".chr(13);

    VerboseEcho($GoogleAddColumns. "<br><br><br>".$GoogleVisualizeColumnsAll);

    //create dataset rows to be processed into google datatable
    $DataForGoogleChart = $DataCollectionArray['GoogleDataRow'];

    //echo "<br><font color='green'>DataForGoogleChart: $DataForGoogleChart</font><br>";

    $GoogleFormattedDataArray = array(
                'GoogleAddColumns' =>    $GoogleAddColumns,
                'GoogleAddRows' =>  $DataCollectionArray['DataTableName'].'.addRows('.$DataCollectionArray['GoogleDataRow'].'); '.chr(13),
                'GoogleVisualizeColumnCount' => $GoogleVisualizeColumnCount,
                'GoogleVisualizeColumnsAvg' => $GoogleVisualizeAvg,
                'GoogleVisualizeColumnsMinStdevStdevMax' => $GoogleVisualizeColumnsMinStdevStdevMax,
                'MainCrosstabSelectQuery' => $DataCollectionArray['MainCrosstabSelectQuery']
    );

    return $GoogleFormattedDataArray;
    }

    //-----------------------------------------------------

    Function DataCollectionCrossTab($SensorString, $TableType, $TimeUnit, $NoAbscissaBins, $TimeStart, $DataTableName) //sensorstring: e.g. DigitalInput 2
    {
    $dbconn = pg_connect("host=10.10.10.8  port=5432 dbname=IpsLogging user=*** password=***")
        or die ('connection aborted: ' . pg_last_error().chr(13));

    switch ($TableType)
        {
        case "boolean":
            $IpsTable = "loggingdb_ips_boolean";
            $AggregateFunctions = "COUNT(*) As value ";
            $SensorColumn = 2;
            $WhereClause=" AND (log.ipsvalue = true) "; //only movement triggers
        break;
        case "integer":
            $IpsTable = "loggingdb_ips_integer";
            $AggregateFunctions = "(AVG(ipsvalue)::NUMERIC(8,2))
                                  ||'', '' ||
                                  (MIN(ipsvalue)::NUMERIC(8,2))
                                  ||'', '' ||
                                  ((AVG(ipsvalue)::NUMERIC(8,2)) - (coalesce(STDDEV(ipsvalue), 0)::NUMERIC(8,2)))
                                  ||'', '' ||
                                  ((AVG(ipsvalue)::NUMERIC(8,2)) + (coalesce(STDDEV(ipsvalue), 0)::NUMERIC(8,2)))
                                  ||'', '' ||
                                  (MAX(ipsvalue)::NUMERIC(8,2))
                                  As value ";
            $WhereClause="";
            $SensorColumn = 4;
        break;
        case "float":
            $IpsTable = "loggingdb_ips_float";
            $AggregateFunctions = "(AVG(ipsvalue)::NUMERIC(8,2))
                                  ||'', '' ||
                                  (MIN(ipsvalue)::NUMERIC(8,2))
                                  ||'', '' ||
                                  ((AVG(ipsvalue)::NUMERIC(8,2)) - (coalesce(STDDEV(ipsvalue), 0)::NUMERIC(8,2)))
                                  ||'', '' ||
                                  ((AVG(ipsvalue)::NUMERIC(8,2)) + (coalesce(STDDEV(ipsvalue), 0)::NUMERIC(8,2)))
                                  ||'', '' ||
                                  (MAX(ipsvalue)::NUMERIC(8,2))
                                  As value ";
            $SensorColumn = 4;
            $WhereClause="";
        break;
        case "string":
            $IpsTable = "loggingdb_ips_string";
            $WhereClause="";
        break;
        }

    Switch ($TimeUnit)
        {case "minutes":
          $SelectRowNames =
            "to_char(ipstimestamp, ''YYYYMMDDHH24MI'') As row_name,
            to_char(ipstimestamp, ''FMHH24h:MI'') As labelled_row_name,
            ''PlaceHolder1'' As PlaceHolder1,
            ''PlaceHolder2'' As PlaceHolder2,
            ''PlaceHolder3'' As PlaceHolder3,";
          $GroupOrder = "
            GROUP BY row_name, labelled_row_name, PlaceHolder1, PlaceHolder2, PlaceHolder3, objectid, category
            ORDER BY row_name, labelled_row_name, PlaceHolder1, PlaceHolder2, PlaceHolder3, objectid, category', ";
        break;

        case "hours":
          $SelectRowNames =
            "to_char(ipstimestamp, ''YYYYMMDDHH24'') As row_name,
            to_char(ipstimestamp, ''FMDD mon FMHH24h'') As labelled_row_name,
            ''PlaceHolder1'' As PlaceHolder1,
            ''PlaceHolder2'' As PlaceHolder2,
            ''PlaceHolder3'' As PlaceHolder3,";
          $GroupOrder = "
            GROUP BY row_name, labelled_row_name, PlaceHolder1, PlaceHolder2, PlaceHolder3, objectid, category
            ORDER BY row_name, labelled_row_name, PlaceHolder1, PlaceHolder2, PlaceHolder3, objectid, category', ";
        break;

        case "days":
          $SelectRowNames =
            "to_char(ipstimestamp, ''YYYYMMDD'') As row_name,
            to_char(ipstimestamp, ''FMDD mon YYYY'') As labelled_row_name,
            ''PlaceHolder1'' As PlaceHolder1,
            ''PlaceHolder2'' As PlaceHolder2,
            ''PlaceHolder3'' As PlaceHolder3,";
          $GroupOrder = "
            GROUP BY row_name, labelled_row_name, PlaceHolder1, PlaceHolder2, PlaceHolder3, objectid, category
            ORDER BY row_name, labelled_row_name, PlaceHolder1, PlaceHolder2, PlaceHolder3, objectid, category', ";
        break;

        case "weeks":
          $SelectRowNames =
            "to_char(ipstimestamp, ''YYYYWW'') As row_name,
            ''wk'' || to_char(ipstimestamp, ''FMWW YYYY'') As labelled_row_name,
            ''PlaceHolder1'' As PlaceHolder1,
            ''PlaceHolder2'' As PlaceHolder2,
            ''PlaceHolder3'' As PlaceHolder3,";
          $GroupOrder = "
            GROUP BY row_name, labelled_row_name, PlaceHolder1, PlaceHolder2, PlaceHolder3, objectid, category
            ORDER BY row_name, labelled_row_name, PlaceHolder1, PlaceHolder2, PlaceHolder3, objectid, category', ";
        break;

        case "months":
          $SelectRowNames =
            "to_char(ipstimestamp, ''YYYYMM'') As row_name,
            to_char(ipstimestamp, ''mon YYYY'') As labelled_row_name,
            ''PlaceHolder1'' As PlaceHolder1,
            ''PlaceHolder2'' As PlaceHolder2,
            ''PlaceHolder3'' As PlaceHolder3,";
          $GroupOrder = "
            GROUP BY row_name, labelled_row_name, PlaceHolder1, PlaceHolder2, PlaceHolder3, objectid, category
            ORDER BY row_name, labelled_row_name, PlaceHolder1, PlaceHolder2, PlaceHolder3, objectid, category', ";
        break;

        case "years":
          $SelectRowNames =
            "to_char(ipstimestamp, ''YYYY'') As row_name,
            to_char(ipstimestamp, ''YYYY'') As labelled_row_name,
            ''PlaceHolder1'' As PlaceHolder1,
            ''PlaceHolder2'' As PlaceHolder2,
            ''PlaceHolder3'' As PlaceHolder3,";
          $GroupOrder = "
            GROUP BY row_name, labelled_row_name, PlaceHolder1, PlaceHolder2, PlaceHolder3, objectid, category
            ORDER BY row_name, labelled_row_name, PlaceHolder1, PlaceHolder2, PlaceHolder3, objectid, category', ";
        break;
        }

    // echo "type ".$IpsTable." <br>";
    $SensorResult = GetSensorNames($SensorString, $TableType, "", "",0, 1);
    // echo "SensorResult: ".$SensorResult.chr(13);
    $CategoryString = implode(", ", pg_fetch_all_columns($SensorResult,$SensorColumn));
    $CategoryArray = pg_fetch_all_columns(GetSensorNames($SensorString, $TableType, "", "",0, 0),5); //array containing the name of each sensor

    // echo "<strong>CategoryString: </strong>". $CategoryString.chr(13)."<br><br><br><br>";
    //Print_r ($CategoryArray);

    //primary query (non-crosstabbed yet)
    $PrimaryQuery ="'SELECT ". $SelectRowNames.
            "varid As category, "
            .$AggregateFunctions
            ." FROM $IpsTable As log
            JOIN ipsobjects_with_parent ips
            ON log.varid = ips.objectid
            WHERE (ips.objectname LIKE ''".$SensorString."'') "
            . $WhereClause . "
            AND (ipstimestamp > (now()- ''". $NoAbscissaBins . " " . $TimeUnit. "''::interval)) ". $GroupOrder ;

    // echo "<strong>PrimaryQuery: $PrimaryQuery</strong>";

    //main crosstab query which pulls all the content data:
    $MainCrosstabSelectQuery =
        "SELECT * FROM crosstab
                    (" .$PrimaryQuery .
        "'SELECT DISTINCT varid
        FROM $IpsTable As log
        JOIN ipsobjects_with_parent ips
        ON log.varid = ips.objectid
        WHERE (ips.objectname LIKE ''".$SensorString."'')
        ORDER BY 1;'
        )

    As CountsPerHour(row_name text,
                    label_row_name text,
                    PlaceHolder1 text,
                    PlaceHolder2 text,
                    PlaceHolder3 text, "
                    .$CategoryString.")";

    //echo "<br><font color='red'>$MainCrosstabSelectQuery</font><br>";

    $QueryResult=pg_query ($dbconn, $MainCrosstabSelectQuery);
    $CrosstabArray = pg_fetch_all($QueryResult);
    //echo "CrosstabArray: " . $CrosstabArray ;
    //$table = good_query_table($CrosstabArray, $QueryResult, 0);
    //BetterTable($QueryResult); //this functions outputs a nicely formatted crosstab!

    if (!$QueryResult)
            echo "PG Error: ". pg_last_error().chr(13);

    // create bracketed Array of Arrays GoogleDataRow
    $GoogleDataRow ="["; //opening bracket inserted
    while ($field = pg_fetch_row($QueryResult))
    {

    $GoogleDataRow .="[";
    $index =0;

    switch ($TableType)
    {
    case "boolean":
    foreach ($field as $col_value) {
            $index++;
            if ($index<6)
                    //the first five columns are strings (date headers)
                    {$GoogleDataRow .= "'".$col_value."', ";}
                else{
                    //anythign above 5 is data
                    //substitute NULL with zeroes, else GoogleChart doesnt work
                    if($col_value == NULL) $col_value = "null";
                    $GoogleDataRow .= $col_value.",    ";
                    }
                }
    break;

    case "integer":
    foreach ($field as $col_value) {
            ++$index;
            if ($index<6)
                    {//the first give columns are strings (date headers)
                    $GoogleDataRow .= "'".$col_value."', ";}
                else{
                    //anythign above 5 is data
                    //substitute NULL with 5x zeroes, else GoogleChart doesnt work
                    if($col_value == NULL) $col_value = "null,null,null,null,null";
                    $GoogleDataRow .= $col_value.",    ";
                    }
                }
    break;

    case "float":
    foreach ($field as $col_value) {
            ++$index;
            if ($index<6)
                    {//the first give columns are strings (date headers)
                    $GoogleDataRow .= "'".$col_value."', ";}
                else{
                    //anythign above 5 is data
                    //substitute NULL with 5x zeroes, else GoogleChart doesnt work
                    if($col_value == NULL) $col_value = "null,null,null,null,null";
                    $GoogleDataRow .= $col_value.",    ";
                    }
                }
    break;

    case "string":
    foreach ($field as $col_value) {
            ++$index;
            if ($index<5)
                    //the first give columns are strings (date headers)
                    {$GoogleDataRow .= "'".$col_value."', ";}
                else{
                    //anythign above 5 is data
                    //substitute NULL with zeroes, else GoogleChart doesnt work
                    if($col_value == NULL) $col_value = 0;
                    $GoogleDataRow .= $col_value." ";
                    }
                }
    break;
    }

    $GoogleDataRow = substr($GoogleDataRow,0,-5)."], ";

    //echo "<br><font color='blue'>$GoogleDataRow </font><br>";
    }

    $GoogleDataRow = substr($GoogleDataRow,0,-2)."]";

    $DataCollectionArray = array(
                        "GoogleDataRow"=>$GoogleDataRow,
                        "NumberOfColumns"=>pg_num_fields($QueryResult), // total number of columns, including all row headers
                        "CategoryArray"=>$CategoryArray,
                        "TableType"=>$TableType,
                        "DataTableName" => $DataTableName,
                        "MainCrosstabSelectQuery" => $MainCrosstabSelectQuery
                        );
    return $DataCollectionArray;
    }

    //---------------------------------------

    function BetterTable($result)
    {
    $i = 0;
    echo "<html>
            <body>
            <table>
            <table class='BetterTable' border='1'>";

    echo "<tr>";
    echo '<td>Line #
    </td>';
    while ($i < pg_num_fields($result))
    {
        $fieldName = pg_field_name($result, $i);
        echo '<td>' . $fieldName . '</td>';
        $i = $i + 1;
    }
    echo '</tr>';
    $i = 0;

    while ($field = pg_fetch_row($result))
    {
            if ($i%2 == 0)
                Echo "<tr bgcolor=\"#d0d0d0\" >";
            else
                Echo "<tr bgcolor=\"#eeeeee\">";
        $fields = count($field);
        $y = 0;
        echo '<td>'.$i. '</td>';
        while ($y < $fields)
        {
            $c_row = current($field);
            echo '<td>'.$c_row . '</td>';
            next($field);
            $y = $y + 1;
        }
        echo '</tr>';
        $i = $i + 1;
    }

    echo '</table><br><br></body></html>';

    }

    //----------------------------------------------------

    Function GetSensorNames($SensorType, $TableType, $prefix, $postfix, $QueryType, $column)
    {//TableType specifies the type of variable, and redirectes to the correct table.
    //prefix and postfix are adapters returned for each row
    //
    //retrieve full names of DataCollection variables, including parent names
    //QueryColumns specifies which query columns (see below)

    $dbconn = pg_connect("host=10.10.10.8  port=5432 dbname=IpsLogging user=*** password=***")
        or die ('connection aborted: ' . pg_last_error().chr(13));

    switch ($TableType)
        {
        case "boolean":
            $IpsTable = "loggingdb_ips_boolean";
        break;
        case "integer":
            $IpsTable = "loggingdb_ips_integer";
        break;
        case "float":
            $IpsTable = "loggingdb_ips_float";
        break;
        case "string":
            $IpsTable = "loggingdb_ips_string";
        break;
        }
    // echo "type ".$IpsTable." <br>";

    if ($prefix!="") $prefix = $prefix." || ";
    if ($postfix!="")$postfix = " || ". $postfix;

    $GetSensorNamesString =
    "SELECT
    DISTINCT '\"' || varid ||'\"' || ' integer ' as integername,
    varid as NakedVariable,
    '\"' || ips.parentname || ' - ' || ips.objectname || ' (' || ips.objectid || ')\"' || ' integer '  AS fullname,
    '\"' || ips.parentname || ' - ' || ips.objectname || ' (' || ips.objectid || ')\"' || ' numeric(8,2) '  AS fullnamenumeric,
    '\"' || ips.parentname || ' - ' || ips.objectname || ' (' || ips.objectid || ')\"' || ' text '  AS fullnamestring,
    '\"' || ips.parentname || ' - ' || ips.objectname || ' (' || ips.objectid || ')\"'  AS fullnamestring,
    ips.parentname || ' - ' || ips.objectname || ' (' || ips.objectid || ')' || ' text '  AS fullnamestringwithoutquotes,
    $prefix varid $postfix as DecoratedVariable

    FROM $IpsTable As log
    JOIN ipsobjects_with_parent ips
    ON log.varid = ips.objectid
    WHERE (ips.objectname LIKE '$SensorType')
    ORDER BY 1;
    ";
    //echo "<strong>$GetSensorNamesString</strong>";

    $QueryResult=pg_query ($dbconn, $GetSensorNamesString);
    if (!$QueryResult)
            echo "PG Error: ". pg_last_error().chr(13);
        else
            {return $QueryResult;}
    }
    //-----------------------------
    Function ColumnLabel($TimeUnit)
    {
    switch ($TimeUnit)
    {
    case "minutes": $ColumnLabel= "0"; break;
    case "hours":   $ColumnLabel= "1"; break;
    case "days":    $ColumnLabel= "2"; break;
    case "months":  $ColumnLabel= "3"; break;
    case "years":   $ColumnLabel= "4"; break;}
    return($ColumnLabel);
    }
    //--------------------------------------------
    function VerboseEcho($Anything)
        {global $Verbose;
        if ($Verbose == true) Echo $Anything;}
    ?>


Trying to add 10 to this.y variable, but returns NaN

I seem to have done something wrong and cant find any solutions. I've tried to convert them into numbers and tried += but i get NaN.

function circle() {
    this.x = 60;
    this.y = 200;
    this.draw = function() {
        ellipse(this.x, this.y, 20, "green");
    };

    this.move = function() {
        $(document).keydown(function(e) {
            //  console.log(e.keyCode);
            if (e.keyCode === 68) {
                this.y += 1;
                console.log(this.y);
            }
        });
    };

}

Might it be because they are not variables?

thanks :)


Strange happenings in the barren wastes of visual studio

So I was just happily going along defining a new class when this happend:

class Thing : public OtherThing
{
public:
    Thing : public OtherThing();//here
};

I really have no idea why visual assist/studio did this and i've never seen it before so really my question is what does it mean?

Just for the sake of clarity I would normally define the same class like this:

class Thing : public OtherThing
{
public:
    Thing();
};


NSButton over QTCaptureView

Is there any way to put NSButton object over QTCaptureView?
I have done following,

In interface builder, added a
QTCaptureView,

Added a button
on top of QTCaptureView and it's
allowing to do so.

When i launch the application, I can see the button over the QTCaptureView but when I start the Camera which will show the Preview in the QTCaptureView session, button is overriding by QTCaptureView.

Any idea what i am doing wrong ?

Basically I need to implement a Control which shows QTCaptureView and a Button over it; when user presses the button then I need to Launch the NSImageView over the QTCaptureView.


PySNMP Instrumentation Controller with asyncio

I need to write simple SNMP responder where part of the job is to call some external script through asyncio.subprocess module. Now I am experimenting with pysnmp but following slightly modified code from examples doesn't work:

import asyncio

from pysnmp.entity import engine, config
from pysnmp.entity.rfc3413 import cmdrsp, context
from pysnmp.carrier.asyncio.dgram import udp
from pysnmp.smi import instrum
from pysnmp.proto.api import v2c

snmpEngine = engine.SnmpEngine()

config.addTransport(
    snmpEngine,
    udp.domainName,
    udp.UdpTransport().openServerMode(('0.0.0.0', 161))
)

# config.addV1System(snmpEngine, 'my-area', 'public')
config.addV1System(snmpEngine, 'public', 'public', contextName='my-context')
config.addV1System(snmpEngine, 'private', 'private', contextName='my-context')

# Allow full MIB access for each user at VACM
config.addVacmUser(snmpEngine, 2, "public", 'noAuthNoPriv', (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1))
config.addVacmUser(snmpEngine, 2, "private", 'noAuthNoPriv', (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1))

# Create an SNMP context
snmpContext = context.SnmpContext(snmpEngine)

# Very basic Management Instrumentation Controller without
# any Managed Objects attached. It supports only GET's and
# always echos request var-binds in response.
class EchoMibInstrumController(instrum.AbstractMibInstrumController):
    @asyncio.coroutine
    def readVars(self, varBinds, acInfo=(None, None)):
        yield from asyncio.sleep(1)
        return [(ov[0], v2c.OctetString('You queried OID %s' % ov[0])) for ov in varBinds]

# Create a custom Management Instrumentation Controller and register at
# SNMP Context under ContextName 'my-context'
snmpContext.registerContextName(
    v2c.OctetString('my-context'),  # Context Name
    EchoMibInstrumController()  # Management Instrumentation
)

# Register GET&SET Applications at the SNMP engine for a custom SNMP context
cmdrsp.GetCommandResponder(snmpEngine, snmpContext)
cmdrsp.SetCommandResponder(snmpEngine, snmpContext)

loop = asyncio.get_event_loop()
loop.run_forever()

When try to make a query with following command snmpget -v 2c -c public 127.0.0.1 .1.3.6.1.2.1.1.1.0 script fails with the following traceback.

Exception in callback AbstractTransportDispatcher._cbFun(<pysnmp.carri...x7f4c7540d518>, ('127.0.0.1', 44209), b'0)\x02\x01\...1\x00\x05\x00')
handle: <Handle AbstractTransportDispatcher._cbFun(<pysnmp.carri...x7f4c7540d518>, ('127.0.0.1', 44209), b'0)\x02\x01\...1\x00\x05\x00')>
Traceback (most recent call last):
  File "/usr/lib/python3.4/asyncio/events.py", line 120, in _run
    self._callback(*self._args)
  File "/opt/profiset2/lib/python3.4/site-packages/pysnmp/carrier/base.py", line 70, in _cbFun
    self, transportDomain, transportAddress, incomingMessage
  File "/opt/profiset2/lib/python3.4/site-packages/pysnmp/entity/engine.py", line 154, in __receiveMessageCbFun
    self, transportDomain, transportAddress, wholeMsg
  File "/opt/profiset2/lib/python3.4/site-packages/pysnmp/proto/rfc3412.py", line 421, in receiveMessage
    PDU, maxSizeResponseScopedPDU, stateReference)
  File "/opt/profiset2/lib/python3.4/site-packages/pysnmp/entity/rfc3413/cmdrsp.py", line 140, in processPdu
    (self.__verifyAccess, snmpEngine))
  File "/opt/profiset2/lib/python3.4/site-packages/pysnmp/entity/rfc3413/cmdrsp.py", line 247, in handleMgmtOperation
    mgmtFun(v2c.apiPDU.getVarBinds(PDU), (acFun, acCtx)))
  File "/opt/profiset2/lib/python3.4/site-packages/pysnmp/entity/rfc3413/cmdrsp.py", line 46, in sendVarBinds
    v2c.apiPDU.setVarBinds(PDU, varBinds)
  File "/opt/profiset2/lib/python3.4/site-packages/pysnmp/proto/api/v1.py", line 135, in setVarBinds
    varBindList.getComponentByPosition(idx), varBind
  File "/opt/profiset2/lib/python3.4/site-packages/pysnmp/proto/api/v1.py", line 38, in setOIDVal
    oid, val = oidVal[0], oidVal[1]
TypeError: 'Future' object does not support indexing

May be I am doing something stupid and I admit that I don't know much about SNMP, then, please, direct me in the right direction.


How do I parse out a text file with AWK and fprint in BASH?

I have a sample.txt file as follows:

Name         City    ST Zip CTY
John Smith   BrooklynNY10050USA
Paul DavidsonQueens  NY10040USA
Michael SmithNY      NY10030USA
George HermanBronx   NY10020USA

Image of input (in case if upload doesn't show properly)
Input

Desired output is into separate columns as shown below:

Desired Output

I tried this:

#!/bin/bash
awk '{printf "%13-s %-8s %-2s %-5s %-3s\n", $1, $2, $3, $4, $5}' sample.txt > new.txt

And it's unsuccessful with this result:

Name          City     ST Zip   CTY

John          Smith    BrooklynNY10050USA

Paul          DavidsonQueens NY10040USA

Michael       SmithNY  NY10030USA

George        HermanBronx NY10020USA

Would appreciate it if anyone could tweak this so the text file will be in delimited format as shown above.  Thank you so much!!


Wordpress Menu with ::after CSS Styling

I want to add the | pipe to the end of each li tag excluding the first and last. is there a better way to do this, was thinking maybe using :nth-child() selector?

 .categoryMenu ul li::after {
         content: ' | ';
    }

.categoryMenu ul li:nth-child(1) {
     content: 'hello';
     background: red;
}

seems that the content css property does not work with :nth-child() only ::after


Multi-Programming with OSMESA

I have being trying to multi-program my software to run on different threads on my client machine with c++; and rendering opengl drawings off-scrren with OSMESA. Does anybody know if its theoretical possible to do this using OSMESA.

Thanks.


Java Dealing with Double values having E

Suppose that I have:

    double Nc= 7.6695805E-4;
    NumberFormat formatter = new DecimalFormat("0.00000000000");
    String string = formatter.format(Nc);
    System.out.println(string);

the output would be:

    0.00076695805

But it is place in string type variable!
What i have to do is to convert it into double or float or long so that it should remain same as 0.00076695805 and so that i can use it for my calculation!
what i have tried is:

    double Nc= 7.6695805E-4;
    NumberFormat formatter = new DecimalFormat("0.00000000000");
    String string = formatter.format(Nc);
    System.out.println(Double.parseDouble(string));

the output becomes:

    7.6695805E-4 //which is same as i gave

so what should be the solution!


CakePHP routing a role to a prefix with a different name

I have the following user roles in my application:

Admin
Client
Contractor

They are controlled by ACL for each function / page.

I want to create a new one called Client_site. But I want this new role to route through to the Client prefixed pages. e.g. /client/:controller/:action

Basically I want it to use all the same pages as the client role, but just have read only access to them. Which I have set up in the ACL tables.

How would I set this up in the routing?

Also is there anything else I will need to amend to get this working?


Tricky WPF binding

I'm unable to do a simple but yet tricky WPF binding in Silverlight 4 (WP7 development)

I have the following code:

Class People{
    public string firstname;
    public string lastname;
}

Class DataSource{
    public static List<People> people; // consider this as a list filled with objects already
}

I'm trying to put the list of people into a ListBox, here's the xaml I've tried:

            <ListBox x:Name="peoplelistbox" Margin="0,0,-12,0" ItemsSource="{Binding DataSource.people}">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                      <StackPanel Margin="0,0,0,17" Width="432">
                            <TextBlock Text="{Binding firstname}" TextWrapping="Wrap"/>
                            <TextBlock Text="{Binding lastname}" TextWrapping="Wrap"/>
                      </StackPanel>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>

But unfortunately my listbox remains empty. What am I doing wrong ?

Thank you in advance :)

Cheers,
Miloud B.


How do I render a fullscreen frame with a different resolution than my display?

I am in the process of teaching myself DirectX development while going through all the tutorials on http://directxtutorial.com/.  I have run into a problem  that I believe is related to me having multiple monitors.

My display is 1920 x 1080.  When my code runs in its current state my primary monitor becomes black with the cursor in the middle.  When I set my SCREEN defines at the top of my code to 1920 x 1080 my program runs fine and displays my sprite with the navy background.  When I leave the SCREEN defines as 1440 x 900 and disable my second monitor my program runs fine.  This is what leads me to believe there is some issue with my second monitor hosing up things.

Any help would be appreciated!

Below is my current code:

    // include the basic windows header files and the Direct3D header file
    #include <windows.h>
    #include <windowsx.h>
    #include <d3d9.h>
    #include <d3dx9.h>

    // define the screen resolution and keyboard macros
    #define SCREEN_WIDTH  1440
    #define SCREEN_HEIGHT 900
    #define KEY_DOWN(vk_code) ((GetAsyncKeyState(vk_code) & 0x8000) ? 1 : 0)
    #define KEY_UP(vk_code) ((GetAsyncKeyState(vk_code) & 0x8000) ? 0 : 1)

    // include the Direct3D Library file
    #pragma comment (lib, "d3d9.lib")
    #pragma comment (lib, "d3dx9.lib")

    // global declarations
    LPDIRECT3D9 d3d;    // the pointer to our Direct3D interface
    LPDIRECT3DDEVICE9 d3ddev;    // the pointer to the device class
    LPD3DXSPRITE d3dspt;    // the pointer to our Direct3D Sprite interface
    BOOL stimToggle = TRUE;

    // sprite declarations
    LPDIRECT3DTEXTURE9 sprite;    // the pointer to the sprite

    // function prototypes
    void initD3D(HWND hWnd); // sets up and initializes Direct3D
    void render_frame(void); // renders a single frame
    void cleanD3D(void); // closes Direct3D and releases memory
    void init_input(HWND hWnd);

    // the WindowProc function prototype
    LRESULT CALLBACK WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);

    // the entry point for any Windows program
    int WINAPI WinMain(HINSTANCE hInstance,
                       HINSTANCE hPrevInstance,
                       LPSTR lpCmdLine,
                       int nCmdShow)
    {
        HWND hWnd;
        WNDCLASSEX wc;

        ZeroMemory(&wc, sizeof(WNDCLASSEX));

        wc.cbSize = sizeof(WNDCLASSEX);
        wc.style = CS_HREDRAW | CS_VREDRAW;
        wc.lpfnWndProc = (WNDPROC)WindowProc;
        wc.hInstance = hInstance;
        wc.hCursor = LoadCursor(NULL, IDC_ARROW);
        wc.hbrBackground = (HBRUSH)COLOR_WINDOW;
        wc.lpszClassName = L"WindowClass1";

        RegisterClassEx(&wc);

        hWnd = CreateWindowEx(NULL,
                              L"WindowClass1",
                              L"Our Direct3D Program",
                              WS_EX_TOPMOST | WS_POPUP,
                              0, 0,
                              SCREEN_WIDTH, SCREEN_HEIGHT,
                              NULL,
                              NULL,
                              hInstance,
                              NULL);

        ShowWindow(hWnd, nCmdShow);

        // set up and initialize Direct3D
        initD3D(hWnd);
        init_input(hWnd);

        // enter the main loop:

        MSG msg;

        while(TRUE)
        {
            //DWORD starting_point = GetTickCount();

            if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
            {
                if (msg.message == WM_QUIT)
                    break;

                TranslateMessage(&msg);
                DispatchMessage(&msg);
            }

            render_frame();

            // check the 'escape' key
            if(KEY_DOWN(VK_ESCAPE))
                PostMessage(hWnd, WM_DESTROY, 0, 0);

            //while ((GetTickCount() - starting_point) < 25);
        }

        // clean up DirectX and COM
        cleanD3D();

        return msg.wParam;
    }

    // this is the main message handler for the program
    LRESULT CALLBACK WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
    {
        switch(message)
        {
            case WM_DESTROY:
                {
                    PostQuitMessage(0);
                    return 0;
                } break;
            case WM_INPUT:
                {
                    RAWINPUT InputData;

                    UINT DataSize = sizeof(RAWINPUT);
                    GetRawInputData((HRAWINPUT)lParam,
                                    RID_INPUT,
                                    &InputData,
                                    &DataSize,
                                    sizeof(RAWINPUTHEADER));

                    // set the mouse button status
                    if(InputData.data.mouse.usButtonFlags == RI_MOUSE_LEFT_BUTTON_DOWN)
                        stimToggle = FALSE;
                    if(InputData.data.mouse.usButtonFlags == RI_MOUSE_LEFT_BUTTON_UP)
                        stimToggle = TRUE;

                    return 0;
                } break;
        }

        return DefWindowProc (hWnd, message, wParam, lParam);
    }

    // this function initializes and prepares Direct3D for use
    void initD3D(HWND hWnd)
    {
        d3d = Direct3DCreate9(D3D_SDK_VERSION);

        D3DPRESENT_PARAMETERS d3dpp;

        ZeroMemory(&d3dpp, sizeof(d3dpp));
        d3dpp.Windowed = FALSE;
        d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
        d3dpp.hDeviceWindow = hWnd;
        d3dpp.BackBufferFormat = D3DFMT_X8R8G8B8;
        d3dpp.BackBufferWidth = SCREEN_WIDTH;
        d3dpp.BackBufferHeight = SCREEN_HEIGHT;
        d3dpp.BackBufferCount = 1;
        d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
        d3dpp.FullScreen_RefreshRateInHz = D3DPRESENT_RATE_DEFAULT;
        d3dpp.EnableAutoDepthStencil = FALSE;

        // create a device class using this information and the info from the d3dpp stuct
        d3d->CreateDevice(D3DADAPTER_DEFAULT,
                          D3DDEVTYPE_HAL,
                          hWnd,
                          D3DCREATE_SOFTWARE_VERTEXPROCESSING,
                          &d3dpp,
                          &d3ddev);

        D3DXCreateSprite(d3ddev, &d3dspt);    // create the Direct3D Sprite object

        D3DXCreateTextureFromFileEx(d3ddev,    // the device pointer
                                    L"ast_sprite.png",    // the new file name
                                    D3DX_DEFAULT,    // default width
                                    D3DX_DEFAULT,    // default height
                                    D3DX_DEFAULT,    // no mip mapping
                                    NULL,    // regular usage
                                    D3DFMT_A8R8G8B8,    // 32-bit pixels with alpha
                                    D3DPOOL_MANAGED,    // typical memory handling
                                    D3DX_DEFAULT,    // no filtering
                                    D3DX_DEFAULT,    // no mip filtering
                                    D3DCOLOR_XRGB(0, 0, 128),    // the hot-pink color key
                                    NULL,    // no image info struct
                                    NULL,    // not using 256 colors
                                    &sprite);    // load to sprite

        return;
    }

    // this is the function used to render a single frame
    void render_frame(void)
    {
        // clear the window to a deep blue
        d3ddev->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0, 0, 128), 1.0f, 0);

        if(stimToggle)
        {
            d3ddev->BeginScene();    // begins the 3D scene
            d3dspt->Begin(D3DXSPRITE_ALPHABLEND);    // begin sprite drawing

            D3DSURFACE_DESC surfaceDesc;
            sprite->GetLevelDesc(NULL, &surfaceDesc);

            // draw the sprite
            D3DXVECTOR3 center(surfaceDesc.Width / 2.0f, surfaceDesc.Height / 2.0f, 0.0f);    // center at the upper-left corner
            D3DXVECTOR3 position(SCREEN_WIDTH / 2.0f, SCREEN_HEIGHT / 2.0f, 0.0f);    // position at 50, 50 with no depth
            d3dspt->Draw(sprite, NULL, &center, &position, D3DCOLOR_XRGB(255, 255, 255));

            d3dspt->End();    // end sprite drawing
            d3ddev->EndScene();    // ends the 3D scene
        }

        d3ddev->Present(NULL, NULL, NULL, NULL);

        return;
    }

    // this is the function that initializes the Raw Input API
    void init_input(HWND hWnd)
    {
        RAWINPUTDEVICE Mouse;
        Mouse.usUsage = 0x02;    // register mouse
        Mouse.usUsagePage = 0x01;    // top-level mouse
        Mouse.dwFlags = NULL;    // flags
        Mouse.hwndTarget = hWnd;    // handle to a window

        RegisterRawInputDevices(&Mouse, 1, sizeof(RAWINPUTDEVICE));    // register the device
    }

    // this is the function that cleans up Direct3D and COM
    void cleanD3D(void)
    {
        sprite->Release();
        d3ddev->Release();
        d3d->Release();

        return;
    }

EDIT:
Here is my debug information from my Output window.

Direct3D9: (INFO) :======================= Hal SWVP device selected

Direct3D9: (INFO) :HalDevice Driver Style b

Direct3D9: :Subclassing window 00680b0a
Direct3D9: :StartExclusiveMode
Direct3D9: :WM_DISPLAYCHANGE: 1440x900x32
Direct3D9: (ERROR) :Lost due to display uniqueness change
Prototype.exe has triggered a breakpoint.

This is where it triggers the breakpoint.  When I click continue, the rest of the below is displayed.

Direct3D9: (INFO) :Using FF to PS converter

Direct3D9: (INFO) :Enabling multi-processor optimizations
Direct3D9: (INFO) :DDI threading started

Direct3D9: (INFO) :Using FF to VS converter in software vertex processing

Direct3D9: (ERROR) :************************************************************
Direct3D9: (ERROR) :ASSERTION FAILED! File s:\gfx_aug09\windows\directx\dxg\inactive\d3d9\d3d\fw\lhbatchfilter.cpp Line 3466: pArgs->Flags.Discard
Direct3D9: (ERROR) :************************************************************
Direct3D9: (ERROR) :************************************************************
Direct3D9: (ERROR) :ASSERTION FAILED! File s:\gfx_aug09\windows\directx\dxg\inactive\d3d9\d3d\fw\lhbatchfilter.cpp Line 3466: pArgs->Flags.Discard
Direct3D9: (ERROR) :************************************************************
Direct3D9: (ERROR) :************************************************************
Direct3D9: (ERROR) :ASSERTION FAILED! File s:\gfx_aug09\windows\directx\dxg\inactive\d3d9\d3d\fw\lhbatchfilter.cpp Line 3466: pArgs->Flags.Discard
Direct3D9: (ERROR) :************************************************************
D3D9 Helper: Warning: Default value for D3DRS_POINTSIZE_MAX is 2.19902e+012f, not 4.16345e-316f.  This is ok.
Direct3D9: :WM_ACTIVATEAPP: BEGIN Activating app pid=00003c58, tid=00005888
Direct3D9: :*** Active state changing
Direct3D9: :WM_ACTIVATEAPP: DONE Activating app pid=00003c58, tid=00005888
Direct3D9: :WM_ACTIVATEAPP: BEGIN Activating app pid=00003c58, tid=00005888
Direct3D9: :*** Already activated
Direct3D9: :WM_ACTIVATEAPP: DONE Activating app pid=00003c58, tid=00005888
Direct3D9: :WM_ACTIVATEAPP: BEGIN Activating app pid=00003c58, tid=00005888
Direct3D9: :*** Already activated
Direct3D9: :WM_ACTIVATEAPP: DONE Activating app pid=00003c58, tid=00005888


How to change the xslt processor used in a .NET program?

How to change xslt processor in .net 2.0?

The question can be vague cause I'm totaly noob with that. I used jetbrain to trace my web app
and I saw that xslt transformation take very long time. I folowed microsoft msdn recommandations
but someone told me to turn (upgrade) my xslt processor to 2.0. to increase performance.

Can you explain me what something about that.


Get all existing users in the database from the given list of user

I have an API which will take list of users as input.
And the output should be all the user who already exits in the database from the list of input users.

One approach I know is to get all the users from the database and loop them all to find if it matches with the input list of users using some programming language.

Other approach is I can send input users list to the database and loop at database end to find the matched user from the input list of users.

But in the above approaches if i have more users in the database it takes long time to process them.

I there any standard algorithm or approach  to handle this kind of problems with more number of records.


What does ((Port *)0x41004400UL) mean here?

I'm working on a developing board that has a 32-bit ARM based microntroller on it (namely the board is Atmel SAM D21J18A). I'm still at the learning phase and I have a lot to go, but I'm really into embedded systems.

I have some background in C. However, it's obviously not enough. I was looking at the codes of an example project by Atmel, and I didn't really get some parts of it. Here is one of them:

    #define PORT              ((Port     *)0x41004400UL) /**< \brief (PORT) APB Base Address */

Port is defined as:

    typedef struct {
        PortGroup             Group[2];    /**< \brief Offset: 0x00 PortGroup groups [GROUPS] */
    } Port;

and PortGroup is defined as:

typedef struct {
    __IO PORT_DIR_Type             DIR;         /**< \brief Offset: 0x00 (R/W 32) Data Direction */
    __IO PORT_DIRCLR_Type          DIRCLR;      /**< \brief Offset: 0x04 (R/W 32) Data Direction Clear */
    __IO PORT_DIRSET_Type          DIRSET;      /**< \brief Offset: 0x08 (R/W 32) Data Direction Set */
    __IO PORT_DIRTGL_Type          DIRTGL;      /**< \brief Offset: 0x0C (R/W 32) Data Direction Toggle */
    __IO PORT_OUT_Type             OUT;         /**< \brief Offset: 0x10 (R/W 32) Data Output Value */
    __IO PORT_OUTCLR_Type          OUTCLR;      /**< \brief Offset: 0x14 (R/W 32) Data Output Value Clear */
    __IO PORT_OUTSET_Type          OUTSET;      /**< \brief Offset: 0x18 (R/W 32) Data Output Value Set */
    __IO PORT_OUTTGL_Type          OUTTGL;      /**< \brief Offset: 0x1C (R/W 32) Data Output Value Toggle */
    __I  PORT_IN_Type              IN;          /**< \brief Offset: 0x20 (R/  32) Data Input Value */
    __IO PORT_CTRL_Type            CTRL;        /**< \brief Offset: 0x24 (R/W 32) Control */
    __O  PORT_WRCONFIG_Type        WRCONFIG;    /**< \brief Offset: 0x28 ( /W 32) Write Configuration */
    RoReg8                         Reserved1[0x4];
    __IO PORT_PMUX_Type            PMUX[16];    /**< \brief Offset: 0x30 (R/W  8) Peripheral Multiplexing n */
    __IO PORT_PINCFG_Type          PINCFG[32];  /**< \brief Offset: 0x40 (R/W  8) Pin Configuration n */
    RoReg8                         Reserved2[0x20];
} PortGroup;

So here, we are looking at the address 0x41004400UL, get the data in there, and then what happens?

I looked up for this but couldn't find anything useful. If you have any suggestions (tutorials, books etc.), please let me hear.


Cannot convert value of type 'Array<String>' to expected argument type 'String?'

I am using WatchConnectivity framework to send an array called watchItems of string value to the apple watch from the phone. I add the watchItems from the sent dictionary and add it to an array called items on the watch to use in a WKInterfaceTable.

The error is occurring for the following line when setting the text of the label to theItem.

for (index, theItem) in self.items.enumerate() {
    let row = self.table.rowControllerAtIndex(index) as! CellRowController
    row.bookmarksCellLabel.setText(theItem)
 }

Heres a full explanation of what I am doing.

iPhone

self.items is an array of NSManagedObjects and each item has a property called title which is a string. So I loop through the objects array and add all the string values to an array called watchItems.

func session(session: WCSession, didReceiveMessage message: [String : AnyObject], replyHandler: ([String : AnyObject]) -> Void) {

    var watchItems = [""]

    for item in self.items {
       watchItems.append(item.title)
    }

    //send a reply
    replyHandler( [ "Value" : [watchItems]])

}

Apple Watch

Here I add the watchItems array from the received message dictionary to the items array on the watch. The watchItems array is an array of string values and so is the items array on the watch.

var items = [String]()

@IBAction func refreshAction() {
    let messageToSend = ["Value":"Hello iPhone"]
    session.sendMessage(messageToSend, replyHandler: { replyMessage in

         let value = replyMessage["Value"] as! String
         self.titleLabel.setText(value)

        }, errorHandler: {error in
            // catch any errors here
            print(error)
    })
}

func session(session: WCSession, didReceiveMessage message: [String : AnyObject], replyHandler: ([String : AnyObject]) -> Void) {

    let value = message["Value"] as! [String]

    dispatch_async(dispatch_get_main_queue()) {
        self.items.removeAll()
        self.items.append(value)
        self.loadTableData()
    }

    //send a reply
    replyHandler(["Value":"Yes"])

}

Function to reload the WKInterfaceTable and set label as each item in the items array.

func loadTableData() {
    table.setNumberOfRows(self.items.count, withRowType: "CellRow")
    if self.items.count > 0 {
        for (index, theItem) in self.items.enumerate() {
            let row = self.table.rowControllerAtIndex(index) as! CellRowController
            row.cellLabel.setText(theItem)
        }
     }
}

I get the error when adding the string value to the cellLabel. Does anybody know where I may be going wrong ?


Shrink image using javascript

I need to shrink the image that was kept in div background-image using javascript.for that image four's side having rounded corner.

Is it possible in javascript?

any suggestions ?


Is there a good and free software to backup a mysql database?

I'm looking for a software or script to make a daily backup (automatic) of a mysql database.
Any suggestions?

Right now my solution is to use Mysql workbench with mysql dump, but I have to do it manually, so anything free and automatic would be appreciated.

Thanks!


Passing an Id from one controller to another

Hi I have this in my mvc 4 application. Once you add a festival to the system and I want to add an event to that festival by passing an id. Can anyone help me? here is my controller along with my view, viewmodel and model. I am getting an error :

The parameters dictionary contains a null entry for parameter 'festID' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Create2(MyFestival.Models.EventsVM, Int32)' in 'MyFestival.Controllers.EventsController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.

    [HttpGet]
    public ActionResult Create2(int festID)
    {
        EventsVM events = new EventsVM { festivalID = festID };

        events.eType = db.EType.ToDictionary(p => p.ID, q => q.EType);
        events.eType.Add(-1, "----- Add New Event Type -----");

        events.eventsDate = DateTime.Now;
        events.startTime = DateTime.Now;
        events.endTime = DateTime.Now;

        return View(events);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create2(EventsVM model, int festID)
    {
        if (ModelState.IsValid != true)
        {
            if (model.selectedEType != -1)
            {
                //db.save stuff from create.
                Events Newevent = new Events();
                Newevent.EndTime = model.endTime;
                Newevent.StartTime = model.startTime;
                Newevent.EventsDate = model.eventsDate = DateTime.Now;
                Newevent.EventsName = model.EventsName;
                Newevent.EType = db.EType.Where(p => p.ID == model.selectedEType).Single();
                Newevent.Location = model.Location;
                if (Request.Files.Count != 0)
                {
                    string fileName = Guid.NewGuid().ToString();
                    string serverPath = Server.MapPath("~\\Content\\EventPicture");
                    Bitmap newImage = new Bitmap(Request.Files[0].InputStream);
                    newImage.Save(serverPath + "\\" + fileName + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
                    model.eventsImage = "Content/EventPicture/" + fileName + ".jpg";

                    Newevent.FestivalID = model.festivalID = festID;

                    db.Events.Add(Newevent);
                    db.SaveChanges();
                    //Change the model.festivalID to Newevent.FestivalID
                    return RedirectToAction("Details", "Festival", new { id = Newevent.FestivalID });
                }
                else
                {
                    db.Events.Add(Newevent);
                    db.SaveChanges();
                    //Change the model.festivalID to Newevent.FestivalID
                    return RedirectToAction("Details", "Festival", new { id = Newevent.FestivalID });
                }
            }
            ModelState.AddModelError("", "No Event Type Picked");
        }

        model.eType = db.EType.ToDictionary(p => p.ID, q => q.EType);
        model.eType.Add(-1, "----- Add New Event Type -----");
        model.eventsDate = DateTime.Now;
        model.startTime = DateTime.Now;
        model.endTime = DateTime.Now;

        return View(model);
    }

Here is my Model

public class Events
{
    [Required]
    public int ID { get; set; }

    [Required]
    public int FestivalID { get; set; }

    [Required(ErrorMessage="Please input the Event Name.")]
    [Display(Name = "Event name"), StringLength(100)]
    [DisplayFormat(ApplyFormatInEditMode = true)]
    public string EventsName { get; set; }

    [Display(Name = "Event date")/*, DataType(DataType.Date)*/]
    [DisplayFormat(DataFormatString = "{0:dd-MMM-yyyy}", ApplyFormatInEditMode = true)]
    [Required(ErrorMessage = "Please input the Event's Date.")]
    public DateTime EventsDate { get; set; }

    [Display(Name = "Start Time"), DataType(DataType.Time)]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:hh:mm tt}")]
    [Required(ErrorMessage = "Please input the Event's Start Time.")]
    public DateTime StartTime { get; set; }

    [Display(Name = "End Time"), DataType(DataType.Time)]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:hh:mm tt}")]
    [Required(ErrorMessage = "Please input the Event's end time.")]
    public DateTime EndTime { get; set; }

    [Required]
    [Display(Name = "Location")]
    [DisplayFormat(ApplyFormatInEditMode = true)]
    public string Location { get; set; }

    [Required]
    [Display(Name = "Event Type")]
    [DisplayFormat(ApplyFormatInEditMode = true)]
    public virtual EventType EType { get; set; }

    [Display(Name = "Event Logo")]
    [DataType(DataType.Upload)]
    [DisplayFormat(ApplyFormatInEditMode = true)]
    public string EventLogo { get; set; }
}

ViewModel

public class EventsVM
{
    [Required]
    [Display(Name = "Event Type")]
    [DisplayFormat(ApplyFormatInEditMode = true)]
    public Dictionary<int, string> eType { get; set; }

    public int selectedEType { get; set; }

    [Required]
    public int ID { get; set; }

    [Required]
    public int festivalID { get; set; }

    [Required]
    [Display(Name = "Event Name"), StringLength(100)]
    [DisplayFormat(ApplyFormatInEditMode = true)]
    public string EventsName { get; set; }

    [Required]
    [Display(Name = "Event Date")/*, DataType(DataType.Date)*/]
    [DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
    public DateTime eventsDate { get; set; }

    [Display(Name = "Start Time"), DataType(DataType.Time)]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:hh:mm tt}")]
    [Required(ErrorMessage = "Please input the Event's Start Time.")]
    public DateTime startTime { get; set; }

    [Display(Name = "End Time"), DataType(DataType.Time)]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:hh:mm tt}")]
    [Required(ErrorMessage = "Please input the Event's end time.")]
    public DateTime endTime { get; set; }

    [Required]
    [Display(Name = "Location")]
    [DisplayFormat(ApplyFormatInEditMode = true)]
    public string Location { get; set; }

    public HttpPostedFileWrapper imageFile { get; set; }
    [Display(Name="Event Image")]
    public string eventsImage { get; set; }
}

And here is my View

@model MyFestival.Models.EventsVM

@{
  ViewBag.Title = "Create Event";
  Layout = "~/Views/Shared/Festival.cshtml";
}

<h2>Add an event for #@Model.festivalID</h2>

@using (Html.BeginForm())
{
@*@using (Html.BeginForm("Create2", "Events", FormMethod.Post, new {enctype="multipart/form-data"}))
{*@
@Html.AntiForgeryToken()

<div class="form-horizontal">
    <hr />
    @Html.ValidationSummary(true)

    <div class="form-group">
        @Html.LabelFor(model => model.EventsName, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            <div class="input-group">
                <span class="input-group-addon"><i class="glyphicon glyphicon-pencil"></i></span>
                <input class="form-control" id="EventsName" required="required" style="width: 210px" name="EventsName" placeholder="Please enter event name" />
                @*@Html.EditorFor(model => model.EventsName, new { @class = "form-control", @style = "width:250px" })*@
            </div>
            @Html.ValidationMessageFor(model => model.EventsName, null, new { @style = "color:red;" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.eventsDate, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            <div class="input-group">
                <span class="input-group-addon"><i class="glyphicon glyphicon-calendar"></i></span>
                @Html.TextBoxFor(model => model.eventsDate, new { @class = "form-control datepicker", @style = "width:210px" })
            </div>
            @Html.ValidationMessageFor(model => model.eventsDate, null, new { @style = "color:red;" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.startTime, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            <div class="input-group">
                <span class="input-group-addon"><i class="glyphicon glyphicon-time"></i></span>
                <input id="startTime" name="startTime" required="required" class="form-control bootstrap-timepicker" style="width: 210px" />
                @*@Html.EditorFor(model => model.startTime, new { @class = "form-control", @style = "width:250px" })*@
            </div>
            @*@Html.EditorFor(model => model.startTime, new { @class = "form-control" })*@
            @Html.ValidationMessageFor(model => model.startTime, null, new { @style = "color:red;" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.endTime, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            <div class='input-group date' id='datetimepicker4'>
                <span class="input-group-addon"><i class="glyphicon glyphicon-time"></i></span>
                <input name="endTime" id="endTime" type='text' class="form-control bootstrap-timepicker" style="width: 210px" />
                @*@Html.TextBoxFor(model => model.startDate, new { @class = "form-control datepicker", @style = "width:210px" })*@
            </div>
            @Html.ValidationMessageFor(model => model.endTime, null, new { @style = "color:red;" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.eType, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            <div class="input-group">
                <span class="input-group-addon"><i class="glyphicon glyphicon-tag"></i></span>
                @Html.DropDownListFor(p => p.selectedEType, Model.eType.Select(p => new SelectListItem() { Text = p.Value.ToString(), Value = p.Key.ToString(), Selected = false }), new { @class = "form-control", @style = "width:210px", @onchange = "checkaddnew();" })
            </div>
            @Html.ValidationMessageFor(model => model.eType, null, new { @style = "color:red;" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Location, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.TextAreaFor(model => model.Location, new { @style = "width:300px;", @class = "form-control", @rows = "3" })
            @Html.ValidationMessageFor(model => model.Location, null, new { @style = "color:red;" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.eventsImage, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            <input name="imageFile" id="File" type="file" />
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-info" />

            @Html.ActionLink("Back to List", "Index", "Festival", null, new { @class = "btn btn-danger" })
        </div>
    </div>
</div>
}

@Html.Partial("CreateEventType", new MyFestival.Models.EventTypeVM())

@section Scripts {
@Scripts.Render("~/bundles/jqueryval")

<script>
    $(document).ready(function () {
        $('#selectedEType').change(function () {
            if ($(this).find(":selected").val() == -1) {
                $('#myModal').modal('show');
            }
        });
    });
</script>

<script type="text/javascript">
    function ajaxResponse(data) {
        alert("This Worked and the Data ID is: " + data.EventTypeID);
        var newOption = "<option value='" + data.EventTypeID + "'>" + data.Name + "</option>";
        $('#selectedEType').append(newOption);
        $('#myModal').modal('hide');

        $("#selectedEType option[value='" + data.EventTypeID + "']").attr("selected", "selected");
    };
</script>

<script type="text/javascript">
    $(document).ready(function () {
        $("#eventsDate").datepicker('setDate', '+1',{dateFormat: "dd/mm/yy"}).on('changeDate', function (ev) {
            $(this).blur();
            $(this).datepicker('hide');
        });
    });
</script>

<script type="text/javascript">
    $('#startTime').timepicker({
        minuteStep: 5,
        showInputs: false,
        disableFocus: true
    });
</script>

    <script type="text/javascript">
        $('#endTime').timepicker({
            minuteStep: 5,
            showInputs: false,
            disableFocus: true
        });
</script>

}


Fluent nHibernate with BindingList<T>

nHibernate is giving the error : Custom type does not implement UserCollectionType: myApp.Domain.OrderLineCollection.

BindingList implements IList, so why is nHibernate trying to use UserCollectionType instead of IList?

public class OrderHeader
{
    public virtual int OrderHeaderId { get; set; }
    public virtual string OrderNumber { get; set; }
    public virtual OrderLineCollection Line { get; set; }
}

public class OrderLineCollection : BindingList<OrderHeader> { }

public class OrderHeaderMap : ClassMap<OrderHeader>
{
    public OrderHeaderMap()
    {
        WithTable("Orders");
        Id(x => x.OrderHeaderId, "OrderId").GeneratedBy.Identity();
        Map(x => x.OrderNumber);
        HasMany(x => x.Line).WithKeyColumn("OrderHeaderId").AsList();
    }
}

<list name="Line">
  <key column="OrderHeaderId" />
  <index />
  <one-to-many class="myApp.Domain.OrderLine, myApp.Domain, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
</list>


Save chosen option in drop down menu after reload

I'm using this drop down menu:

HTML:

<ul id="dropdown">
    <li> Choose theme
    <ul>
        <li id="stylesheet1" > <a href="#"> Default </a></li>
        <li id="stylesheet2" > <a href="#"> Theme 1 </a></li>
        <li id="stylesheet3" > <a href="#"> Theme 2 </a></li>
        <li id="stylesheet4" > <a href="#"> Theme 3 </a></li>

    </ul>
</li>
</ul>

And this is the CSS:

#dropdown {
 float: left;
 margin: 0;
 padding: 0;
 }
#dropdown li {
 background: #F7F0E0;
 border:1px solid #666;
 float: left;
 list-style: none;
 margin: 0;
 padding:0 0 0 10px;
 position: relative;
 height:20px;
 width:100px;
}
#dropdown li:hover {
 background: #FF2828;
}
#dropdown li a {
 text-decoration:none;
}
#dropdown ul {
 background: #F7F0E0;
 display: none;
 margin: 0;
 padding: 0;
 position: absolute;
 top: 20px;
 left: -1px;
 z-index: 500;
}
 #dropdown ul {
 position: absolute;
   }
 #dropdown li:hover ul {
 display: block;
 }

Is it possible that the option chosen is kept for the next time the page reloads? Or should I make another drop down, for example:

<form>
<select id="myList" >
  <option id="stylesheet1">Default</option>
  <option id="stylesheet2">Theme 1</option>
  <option id="stylesheet3">Theme 2</option>
  <option>Theme 3</option>
</select>

<form>

I am using javascript and cookies on my page, should I use this to be able to this as well?


Cimg border reading

#include "CImg.h"
#include <iostream>
#include <string>
#include <sstream>
#include<math.h>

using namespace std;
using namespace cimg_library;

class Imagen{
public:

CImg<int> contorno(char[60]);
CImg<int> binarizar(char[60],int);
CImg<int> grises(char[60]);};

CImg<int> Imagen::binarizar(char nombreImagen[60],int factorB){
CImg<int> imagen(nombreImagen);
unsigned char r,g,b,promedio;
CImg<int> imagenB(imagen.width(),imagen.height(),1,1);
for(int x=0;x<imagenB.width();x++){
    for(int y=0;y<imagenB.height();y++){
            r=imagen(x,y,0,0);
            g=imagen(x,y,0,1);
            b=imagen(x,y,0,2);
            promedio=((r+g+b)/3);

            if( promedio>=factorB)
                imagenB(x,y,0,0)=255;

            if( promedio<=factorB)
                imagenB(x,y,0,0)=0;

    }}

return imagenB;}

CImg<int> Imagen::grises(char nombreImagen[60]){
CImg<int> imagen(nombreImagen);
CImg<int> imagenG(imagen.width(),imagen.height(),1);
cimg_forXYC(imagen,x,y,c) {
   imagenG(x,y,0)= (imagen(x,y,0)+imagen(x,y,1)+imagen(x,y,2))/3;
}
return imagenG;}

CImg<int> Imagen::Contorno(char nombreImagen[60]){
CImg<int>imagen(nombreImagen);
CImg<int>imagenCont(imagen.width(),imagen.height(),1);
 CImg<int>imagenGris2(imagen.width(),imagen.height(),1);
int a,b,c,d;
for(int x=0;x<imagen.width();x++){
    for(int y=0;y<imagen.height();y++){
            imagenGris2=(imagen(x,y,0)+imagen(x,y,1)+imagen(x,y,2))/3;
            a = imagenGris2(x,y,0);
            b = -imagenGris2(x+1,y+1,0);
            c = imagenGris2(x+1,y,0);
            d = -imagenGris2(x,y+1,0);
        imagenCont(x,y,0) = (sqrt(pow((a+b),2)+pow((c+d),2)));

    }
}
return imagenCont; }

int main () {

Imagen img;
char nomImg [60];
int opcion, factorBinarizar;
cout<<"ñññ."<<endl<<endl;
cout<<"Manipulacion de Imagenes Basica."<<endl<<endl;
cout<<"Ingrese el nombre de la imagen: "<<endl;
cin>>nomImg;

do{
    CImg<int> nvaImagenGris, nvaImagenBin, nvaImagenCont;
    cout<<"Seleccione una opcion:"<<endl<<endl<<"[1].visualizar escala de grises.\n[2].Visualizar la imagen binarizada.\n[3].Visualizar contornos de la imagen.\n[4].Guardar las imagenes y salir.\n";
    cin>>opcion;

    switch(opcion){
        case 1:nvaImagenGris=img.grises(nomImg);break;
        case 2:
            cout<<"Ingrese el numero factor de binarizacion:"<<endl;
            cin>>factorBinarizar;
            nvaImagenBin=img.binarizar(nomImg,factorBinarizar);
            break;
        case 3:
            nvaImagenCont=img.Contorno(nomImg);
            break;
        case 4:
            nvaImagenGris.save("ImModGris.bmp");
            nvaImagenBin.save("ImModBin.bmp");
            nvaImagenCont.save("ImModCont.bmp");
        break;
        default:
            cout<<"opcion incorrecta"<<endl;
        break;
    }
    if(opcion==1){
        CImgDisplay ventana(nvaImagenGris, "Imagen grises",1 );
        ventana.wait(3000);}
        else if (opcion==2){
        CImgDisplay ventaNa(nvaImagenBin, "Imaen Binarizada",1 );
        ventaNa.wait(3000);}
        else if (opcion==3){
        CImgDisplay ventanA(nvaImagenCont,"Contorno de la Imagen",1);
        ventanA.wait(3000);}

}while(opcion != 4);
return 0;}

I have problems with the "contorno" method, it is suposed to show only de borders of a .bmp image, but instead it shows me a black window, I am new using CImg so I don't know why this is happening, any idea and/or solution for this?

I'm using code::blocks on a windows 10 OS.


What programming language/compiler/libraries should I use to create an app that runs on Windows XP without any additional software?

I need to create a basic app to check the availability of components and if necessary download them to any computer running Windows XP or above. Which language (preferably free or VS 2010) should I use to create such an application which can run without requiring any frameworks installed beforehand?


Collapse panel javascript issues

I have a collapsible panel extender. I have no issues with the extender. however, I have a link that opens the panel and I want another link saying collapse to close it. I want to hide one show one javascript side. The issue is that it only works for the first row but not the others because I am not getting the unique ID or something. I haven't found a legitimate answer yet. I've tried jquery by getting parent elements and I was unsuccessful. What can I do?

Answer:

<asp:TemplateField HeaderText="Lng Descr" SortExpression="LongDescription">
                <EditItemTemplate>
                    <asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("LongDescription") %>' TextMode ="MultiLine" Rows="5" ></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                <table>
                    <tr id="expand" style="display:">
                        <td>
                            <asp:Label ID="Label3" runat="server" ForeColor="Blue"><u></u></asp:Label>
                        </td>
                    </tr>
                </table>
                <asp:Panel ID="Panel1" runat="server" >
                    <table>
                    <tr>
                    <td>
                        <%#Eval("LongDescription")%>
                    </td>
                    </tr>
                    </table>
                </asp:Panel>
                <ajaxToolkit:CollapsiblePanelExtender ID="cpe" runat="Server"
                 TargetControlID = "Panel1"
                 CollapsedSize="0"
                ExpandedSize="50"
                Collapsed="true"
                ExpandControlID="Label3"
                CollapseControlID="Label3"
                AutoCollapse="false"
                Scrollcontents="false"
                collapsedText="<u>Expand"
                ExpandDirection="Vertical"
                ExpandedText = "<u>Collapse"
                TextLabelID="Label3" />
                </ItemTemplate>
            </asp:TemplateField>


Reproducible CFQUERYPARAM performance issue in Coldfusion 10

I've consistently been able to reproduce a serious parameterization performance issue with Coldfusion 10 querying SQL Server 2008 R2 and would be interested to know what others get. The code is below.

What does the test do?
It creates a table with 100 rows. A data column is blank in all but one. It then runs a Coldfusion query 10 times, half using cfqueryparam and half using a simple string. It returns a list with the response time for each. When I run this, apart from the initial calls, the parameterized query runs much more slowly (by about 10-100 times).

What's happening in SQL Server?
I can see no difference in SQL server. In both cases the plan cache indicates virtually identical plans (one is obviously parameterized) and the profiler shows fast responses for both. However, Coldfusion struggles with the parameterized query.

What fixes the issue?
Curiously, if I change the varchar to an nvarchar, the problem goes away. Or if I move the non-blank to the start, then both responses are slow (go figure). If I make all records blank or non-blank then again the issue isn't there. It must be a mix. I can't reproduce the issue in CF9 but haven't tried CF11.

<cfset datasource="yourdatasource" />
<cfquery name="createdata" datasource="#datasource#">
    --EMPTY PREVIOUS TESTS
    IF OBJECT_ID('aaatest', 'U') IS NOT NULL
    BEGIN
        TRUNCATE TABLE aaatest;
        DROP TABLE aaatest;
    END

    --CREATE TABLE TO CONTAIN DATA
    CREATE TABLE [dbo].[aaatest](
        [id] [int] NOT NULL,
        [somedata] [varchar](max) NULL,
        [somekey] [int] NOT NULL
    ) ON [PRIMARY];

    --INSERT 100 ROWS WITH 99 BLANK AND 1 NON-BLANK
    WITH datatable AS (
        SELECT 1 id
        UNION all
        SELECT id + 1
        FROM    datatable
        WHERE   id + 1 <= 100
    )
    INSERT INTO aaatest(id,somekey,somedata)
    SELECT id,1,case when id=99 then 'A' else '' end
    FROM datatable;
</cfquery>

<cfset results=[] />
<cfloop from="1" to="10" index="n">
    <!--- use parameters for every other test --->
    <cfset useParameters = (n mod 2 is 0) />
    <cfquery name="myquery" datasource="#datasource#" result="result">
        SELECT  somedata
        FROM    aaatest
        WHERE  somekey=
        <cfif useParameters>
            <cfqueryparam value="1" CFSQLType="CF_SQL_INTEGER" />
        <cfelse>
            1
        </cfif>
    </cfquery>
    <!--- store results with parameter test marked with a P --->
    <cfset arrayAppend(results,(useParameters?'P':'')&result.executiontime) />
</cfloop>

<cfdump var="#results#" />


Piping results with dplyr to fitdist package

I'm trying to group a set of data by "Area" and then get R to do a fitdist analysis on each of the Area groups.  For some reason I can not do the piping correctly to pass the variable "cpl" to the fitdist function.  Am I doing something obviously wrong?  I've attempted many permutations but no luck so far.  The variable cpl does exist.

> str(ccpldw2)

'data.frame':   149 obs. of  2 variables:
 $ Area: Factor w/ 4 levels "2","4","5","7": 1 1 1 1 1 1 1 1 1 1 ...
 $ cpl : num  0.0007 0.0007 0.0007 0.0007 0.0009 0.0019 0.0022 0.003 0.003 0.0031 ...

results <- group_by(ccpldw2, Area) %>%  fitdist(cpl, "lnorm")

Error in fitdist(., cpl, "lnorm") : object 'cpl' not found

Apologies, here is a MWE,

rm(list=ls())

library(fitdistrplus)
library(dplyr)

inputdata <- data.frame(Area = as.factor (rep(c(2,3,7),10)),
                        cpl = rlnorm(30, -5.07, 1.04))

results <- group_by(inputdata, Area) %>% fitdist(cpl, "lnorm")

Which gives me this error.

Error in fitdist(., cpl, "lnorm") : object 'cpl' not found


How to know if a user clicked play on a video

I do not even know where to start with this but what I want to do is I want to be able to know if someone has clicked play on a video on my site. The code for the video embed is:

<div class="gv-placement-sap" id="gv_target_7196907613889253931538584">
</div>

<script>!function(a,b,c){var d=a.getElementsByTagName(b)[0];a.getElementById(c)||(a=a.createElement(b),a.id=c,a.src=("https:"==document.location.protocol?"http://player-services.goviral-content.com".replace(/^http\:/,"https:"):"http://player-services.goviral-content.com")+"/embed-code/index/find?placementVersionId=7196907613889253931538584",d.parentNode.insertBefore(a,d))}(document,"script","gv_script_7196907613889253931538584");</script>

Any help is appreciated..thanks


Error redirection in WebView

I'm developing a browser-like application in android using WebView.
While loading the URL, I want to display a specific page/message/toast whenever server returns 404 response. I tried using shouldOverrideUrlLoading, but it can filter URLs based on URL string only. Is there any good way to get the server's response code within WebViewClient or WebChromeClient (without loading the URL twice)?


How to remove heroku ssh keys that don't have a name

The heroku docs mention how to remove ssh keys that have a name associated with them using heroku keys:remove:

https://devcenter.heroku.com/articles/keys

But I have managed to upload some keys that don't have a name and now can't find a way to delete them. The heroku keys:remove command expects a name to be specified.

Is there some other way to clear ssh keys associated with an account?


How to install this github ruby(gem) project on my ubuntu system?

I am new to Ruby and this project is a ruby gem.
Link to the project https://github.com/cheerfulstoic/music.
I can't find any steps to setup this project.


How does += (plus equal) work?

I'm a bit confused with the += sign. How does it work?

1 += 2 // equals ?

and this

var data = [1,2,3,4,5];
var sum = 0;
data.forEach(function(value) {
    sum += value;
});
sum = ?


Require TextBox depending on RadioButtonList selection in Repeater

I have a repeater with a RadioButtonList and TextBox inside. I want the TextBox to be required only if the RadioButtonList has a value of 1 or 2. How can I achieve this?

I thought I could initially enable the RFV on a selected index change but it can't see the items since it is within a repeater. Do I need to do this within the ItemDataBound?

<asp:Repeater ID="repeaterSurvey" runat="server">
   <ItemTemplate>
      <div class="form-group">
         <asp:Label ID="labelQuestion" runat="server" Text='<%# Eval("Question")%>' />
         <asp:RequiredFieldValidator ID="RFV1" CssClass="required" runat="server"
          ErrorMessage="Required" Display="Dynamic" ControlToValidate="surveyList" />

         <asp:RadioButtonList RepeatDirection="Horizontal" ID="surveyList" AutoPostBack="true"
          OnSelectedIndexChanged="surveyList_SelectedIndexChanged" runat="server">
            <asp:ListItem Value="1">Strongly Disagree</asp:ListItem>
            <asp:ListItem Value="2">Disagree</asp:ListItem>
            <asp:ListItem Value="3">Agree</asp:ListItem>
            <asp:ListItem Value="4">Strongly Agree</asp:ListItem>
            <asp:ListItem Value="0">N/A</asp:ListItem>
         </asp:RadioButtonList>
         <asp:HiddenField ID="hiddenfieldID" Value='<%# Eval("ID")%>' runat="server" />
         <asp:TextBox ID="textboxComment" Placeholder="Comments" CssClass="form-control" TextMode="MultiLine"
          Rows="3" runat="server"></asp:TextBox>
         <asp:RequiredFieldValidator ID="RFV2" Enabled="false" CssClass="required" runat="server"
          ErrorMessage="Comment Required" Display="Dynamic" ControlToValidate="textboxComment" />
      </div>
   </ItemTemplate>
</asp:Repeater>

Codebehind

protected void surveyList_SelectedIndexChanged(object sender, System.EventArgs e)
{
   if (surveyList.SelectedValue == "1" || surveyList.SelectedValue == "2")
   {
      RFV2.Enabled = true;
   }
   else
   {
      RFV2.Enabled = false;
   }
}


how to create custom grid view programatically in android?

I want to create custom grid view where grid view first image will be parent match only width and else image view 100 x 100. Grid view depend on arraylist values


Session variables are not persisting between page loads

I try to create a session to be available for PHP pages.

But it is not working.

Test1.php

session_start();
$_SESSION["current_id"] = 7 ;

echo "Current id : " .  $_SESSION['current_id'] . "</br>" ;
if (!is_writable(session_save_path())) {
    echo 'Session path "' . session_save_path() . '" is not writable for PHP!'; }
else {
    echo 'Session path "' . session_save_path() . '" is Writable for PHP!'; }
echo("</br>");
var_dump($_SESSION);

Result:

Current id : 7

  Session path "/var/lib/php5" is Writable for PHP!
      /home/ubuntu/workspace/CRF/main1.php:58: array(1) { 'current_id' => string(1) "7" }

Tets2.php

session_start();
echo "Current id : " .  $_SESSION['current_id'] . "</br>" ;
echo("</br>");
var_dump($_SESSION);

Result:

Current id : /home/ubuntu/workspace/CRF/workflow.php:108: array(0) { }

Any Ideas?


how to take the phone number

i want to take the phone number from the phone dialer to use it in my application for that
i used this code in the manifest file

           <uses-permission android:name="android.permission.READ_PHONE_STATE" />

         <intent-filter >

         <action android:name="android.intent.action.CALL" />

         <action android:name="android.intent.action.CALL_PRIVILEGED" />

          <category android:name="android.intent.category.DEFAULT" />
           <data android:scheme="tel" />

and to get the phone number that i call , so i did  use this method

 TelephonyManager phoneManager = (TelephonyManager)
              getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE);
        String phoneNumber = phoneManager.getLine1Number();

but its return null when no sim card and nothing when its included

so  is there any other method to get the phone number that i use into my application


aChartEngine shows two charts instead one

please look at the images, the first is the adb emulator and the second is a Samsung Galaxy Tab.

Image1 Image 1 http://i41.tinypic.com/qph4kl.png

Image2 Image 2 http://i41.tinypic.com/2czzwpg.jpg

I don't know why in the Tab aChartEngine shows two charts.

This is the code:

`private void MostrarCurvas(Estructuras.DatosCurva curva_uno, Estructuras.DatosCurva curva_dos) { XYSeries uno = new XYSeries("Adquisicion");
XYSeries dos = new XYSeries("Interpolacion");

for (int i = 0; i < curva_uno.b.Length; i++)
{
    uno.Add(curva_uno.a[i], curva_uno.b[i]);
}

for (int i = 0; i < curva_dos.b.Length; i++)
{
    dos.Add(curva_dos.a[i], curva_dos.b[i]);
}

XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
dataset.AddSeries(uno);
dataset.AddSeries(dos);

XYSeriesRenderer unoRender = new XYSeriesRenderer();
unoRender.Color = Color.Blue;
unoRender.PointStyle = PointStyle.Point;
unoRender.LineWidth = 1;

XYSeriesRenderer dosRender = new XYSeriesRenderer();
dosRender.Color = Color.Green;
dosRender.PointStyle = PointStyle.Point;
dosRender.LineWidth = 1;

XYMultipleSeriesRenderer multiRenderer = new XYMultipleSeriesRenderer();
multiRenderer.XTitle = "(V)";
multiRenderer.YTitle = "(I)";

multiRenderer.AddSeriesRenderer(unoRender);
multiRenderer.AddSeriesRenderer(dosRender);

LinearLayout layout = FindViewById<LinearLayout>(Resource.Id.graph);
GraphicalView ChartView = ChartFactory.GetLineChartView(this, dataset, multiRenderer);

layout.AddView(ChartView); }`


Value of submit button clicked

This should be really straight forward.

I'm checking if a form is being submitted using jquery. The form has multiple submit buttons with various values:

<button type="submit" value="foo">Foo</button>
<button type="submit" value="bar">Bar</button>

I would like to find the value of the button that just submitted the form:

$(form).live('submit', function() {
    // Get value of submit button
}

Thanks


Strongname Signing IKVM PDFBox for Word Addin

for a Word Addin I am using PDFBox to manipulate PDFs. Or rather I would like to use it. I used it before with a self-created Desktop App. PDFBox is a Java Library that can be made usable as DLLs with IKVM (like here: http://www.squarepdf.net/pdfbox-in-net ). The problem that I experience is that all libraries for Wordaddins must be strongnamed. I tried to strongname sign but then I get an exception that a part of apache common logging (in directory MANIFEST.MF) cannot be found.
I know this is pretty vague so far and I will post more details later on, but maybe someone already went through this and has an idea on how to do this right or can point me to some place where there is already a strongnamed version of PDFBox.
Thanks in advance!


C: Error at accessing dynamically allocated elements

I am trying to write a function that searches a certain element. However, it exists with error when I try to access an element. I commented the rows that generate the error in search function.

#include <stdlib.h>
#include <stdio.h>
#define m 2

typedef struct pag {
    int nr;
    int key[m];
    struct pag * child[m + 1];
}* page;

page init(page B) {
    int i;
    B = malloc(sizeof(struct pag));

    for (i = 0; i < m; i++) {
        B->key[i] = 0;
        B->child[i] = malloc(sizeof(struct pag));
    }
    B->child[i] = malloc(sizeof(struct pag));
    return B;
}

page search(page B, int k) {
    int i;
    if (B == NULL )
        return B;
    // 1. cautare liniara
    for (i = 0; i < m; i++) {
            // 2. find the desired value
        if (B->key[i] == k) {
            return B;
            // 3. find the value greater or equal, take the left road to the child
        } else if (B->key[i] >= k) {
            return search(B->child[i], k); //exists with error here
        }
    }

    return search(B->child[i], k); //also exists with error here
}

int main() {
    page B = init(B);

    if (search(B, 2) == NULL )
        printf("Negasit");
    else
        printf("Gasit");

    return 0;
}


Sum Query in Elasticsearch

I'm fairly new to Elasticsearch.  I'm trying to write a query that will group by a field and calculate a sum.  In SQL, my query would look like this:
SELECT lane, SUM(routes) FROM lanes GROUP BY lane

I have this data that looks like this in ES:

{
  "_index": "kpi",
  "_type": "mroutes_by_lane",
  "_id": "TUeWFEhnS9q1Ukb2QdZABg",
  "_score": 1.0,
  "_source": {
    "warehouse_id": 107,
    "date": "2013-04-08",
    "lane": "M05",
    "routes": 4047
  }
},
{
  "_index": "kpi",
  "_type": "mroutes_by_lane",
  "_id": "owVmGW9GT562_2Alfru2DA",
  "_score": 1.0,
  "_source": {
    "warehouse_id": 107,
    "date": "2013-04-08",
    "lane": "M03",
    "routes": 4065
  }
},
{
  "_index": "kpi",
  "_type": "mroutes_by_lane",
  "_id": "JY9xNDxqSsajw76oMC2gxA",
  "_score": 1.0,
  "_source": {
    "warehouse_id": 107,
    "date": "2013-04-08",
    "lane": "M05",
    "routes": 3056
  }
},
{
  "_index": "kpi",
  "_type": "mroutes_by_lane",
  "_id": "owVmGW9GT345_2Alfru2DB",
  "_score": 1.0,
  "_source": {
    "warehouse_id": 107,
    "date": "2013-04-08",
    "lane": "M03",
    "routes": 5675
  }
},
...

I want to essentially run the same query in ES as I did in SQL, so that my result would be something like (in json of course): M05: 7103, M03: 9740


nunit setup/teardown not working?

Ok, I've got a strange problem. I am testing a usercontrol and have code like this:

[TestFixture]
public myTestClass : UserControl
{
    MyControl m_Control;

    [Test]
    public void TestMyControl()
    {
        m_Control = new MyControl();
        this.Controls.Add(m_Control);

        Assert.That(/*SomethingOrOther*/)
    }
}

This works fine, but when I change it to:

[TestFixture]
public myTestClass : UserControl
{
    MyControl m_Control;

    [Setup]
    public void Setup()
    {
        m_Control = new MyControl();
        this.Controls.Add(m_Control);
    }

    [TearDown]
    public void TearDown()
    {
        this.Controls.Clear();
    }

    [Test]
    public void TestMyControl()
    {
        Assert.That(/*SomethingOrOther*/);
    }
}

I get an Object Reference Not Set To An Instance of an Object. I even output to the console to ensure that the setup/teardown were running at the correct times, and they were... but still it isn't newing up the usercontrols.

edit> The exact code is:

[TestFixture]
public class MoneyBoxTests : UserControl
{
    private MoneyBox m_MoneyBox;
    private TextBox m_TextBox;

    #region "Setup/TearDown"
    [SetUp]
    public void Setup()
    {
        MoneyBox m_MoneyBox = new MoneyBox();
        TextBox m_TextBox = new TextBox();

        this.Controls.Add(m_MoneyBox);
        this.Controls.Add(m_TextBox);
    }

    [TearDown]
    public void TearDown()
    {
        this.Controls.Clear();
    }
    #endregion

    [Test]
    public void AmountConvertsToDollarsOnLeave()
    {
        m_MoneyBox.Focus();
        m_MoneyBox.Text = "100";
        m_TextBox.Focus();

        Assert.That(m_MoneyBox.Text, Is.EqualTo("$100.00"), "Text isn't $100.00");
    }

    [Test]
    public void AmountStaysANumberAfterConvertToDollars()
    {
        m_MoneyBox.Focus();
        m_MoneyBox.Text = "100";
        m_TextBox.Focus();

        Assert.That(m_MoneyBox.Amount, Is.EqualTo(100), "Amount isn't 100");
    }
}

I get the exception(s) at the respective m_MoneyBox.Focus() calls.

Solved - See Joseph's comments


Error: can't find any special indices 2d (needs index) 2dsphere (needs index)

When i use this find command on heroku cloud server:

users.find({$and: [
{loc: { $nearSphere: user.loc.coordinates,
        $maxDistance: user.dis / 3959}},
{age: {$gte: user.age_down}},
{age: {$lte: user.age_up}},
{gender: user.interested},
{interested: user.gender}]})

i get the can't find any special indices 2d (needs index) 2dsphere (needs index) Error.

the results (in heroku) of the db.users.getIndexes() are:

PRIMARY> db.getIndexes()
[
        {
                "v" : 1,
                "key" : {
                        "_id" : 1
                },
                "ns" : "app27206755.users",
                "name" : "_id_"
        },
        {
                "v" : 1,
                "key" : {
                        "loc" : "2dsphere"
                },
                "ns" : "app27206755.users",
                "name" : "loc_2dsphere",
                "background" : true
        }
]

the weird thing is that in my local server it works perfectly (the same code exactly) but the problem is only on heroku.. i think that maybe i have a newer version of mongo on my local machin. the problem is that i dont know how to update the version of mongodb on the heroku cloud server, or if its even possible?

Update: i just found that the version of mongo in heroku is 2.4.8 and in my local machine is 2.6.3.
any idea how to upgrade ?

thanks !


using AND condition MYsql

What I need is: when I give training_id 172 AND training_id 174 it have to return user 150 only

I tried this but it doen't work

SELECT user_id FROM Training_users WHERE training_id = 172 AND training_id = 174

Most of the times training_id might be more than 2


Append document to iFrame

I am currently receiving parts of a webpage through an XHR, and then parsing them using the DOMParser. After this I change some of the elements, but I am failing to append the document to the iFrame.

The document that is parsed is all right, but when appending this document to the iFrame by calling iFrame.contentDocument = parsedDocument, iFrame.contentDocument stays empty (actually there are html, head and body tags but their content is empty).

I am parsing the received data like so:

var parser = new DOMParser();
var parsedDocument= parser.parseFromString(xhr.response, 'text/html');

And my expectation was to do something like this:

iFrame.contentDocument = parsedDocument;