text:
Q: dc linecharts in a composite chart with group reduction using reduce callback methods I want to make a composite chart with an unknown number of lincharts all based on the same dimension but each of them with call-back reduction functions to calculate count, sum and average but every one filtering data for a given field value of the dimension.
I don't know how to make it work. The graph coordinates and legends appear but no line is painted.
This is what I'm currently doing:
var tablaCount = dc.dataCount("#dataCount");
var tablaDatos = dc.dataTable("#tabla");

var ofs = 0, pag = 10, ndxSize = 0;
var ndx, all;
d3.json("/PruebaConcepto/json/userdashboard-vgodoy-pruebax_20181023111343.json").then(function(data) {
    ndx = crossfilter(data);
    ndxSize = ndx.size();
    all = ndx.groupAll();

    var compositeChartline1 = dc.compositeChart("#lineChartline1");
    var dimensionline1 = ndx.dimension(function(d) { return [d.horasacta, d.aerodromo] ; });
    var groupline1 = dimensionline1.group().reduce(
    function (p, v) {
        ++p.count;
        p.pct = (p.count / ndxSize) * 100;
        p.sum += ("viento_int_viento" != "kpigroup" ? (v.viento_int_viento ? v.viento_int_viento : 0) : 0);
        p.avg = ((p.sum ? p.sum : 0) / p.count);
        return p;
    },
    function (p, v) {
        --p.count;
        p.pct = (p.count / ndxSize) * 100;
        p.sum -= ("viento_int_viento" != "kpigroup" ? (v.viento_int_viento ? v.viento_int_viento : 0) : 0);
        p.avg = ((p.sum ? p.sum : 0) / p.count);
        return p;
    },
    function () {
        return {count: 0, pct: 0, sum: 0, avg: 0};
    }
    );

    var keysline1 = groupline1.all().filter(function(d) {return d.key[0]});
    var seriesline1 = [];
    var tmpseriesline1 = [];
    for (var i = 0; i < keysline1.length; i++) {
        tmpseriesline1.push(keysline1[i].key[1]);
    }
    seriesline1 = (tmpseriesline1.filter(function(item, pos) { return tmpseriesline1.indexOf(item) == pos;})).slice();
    tmpseriesline1 = 0;

    var yMaxline1 = 0;
    for (var i = 0; i < groupline1.size() && !(groupline1.top(Infinity)[i] == null); i++) {
        if (yMaxline1 < groupline1.top(Infinity)[i].value.avg) {
        yMaxline1 = groupline1.top(Infinity)[i].value.avg;
        }
    }
    var yMagline1 = Math.pow(10, Math.floor((Math.log(yMaxline1) / Math.LN10 + 0.000000001))) / 10;
    yMaxline1 = Math.ceil(yMaxline1 + yMagline1);

    var xRangeline1 = [];
    var tmpxRangeline1 = [];
    for (var i = 0; i < keysline1.length; i++) {
        tmpxRangeline1.push(keysline1[i].key[0]);
    }
    xRangeline1 = tmpxRangeline1.filter(function(item, pos) { return tmpxRangeline1.indexOf(item) == pos;});
    tmpxRangeline1 = 0;

    var color = ["red", "green", "yellow"];
    var groupsline1 = [seriesline1.length];
    var lineChartsline1 = [seriesline1.length];
    for (var i = 0; i < seriesline1.length; i++) {
    var tmpSeriesline1 = seriesline1[i]
    var tmpGroupline1 = dimensionline1.group().reduce(
                                    function (p, v) {
                                        ++p.count;
                                        p.pct = (p.count / ndxSize) * 100;
                                        p.sum += ("viento_int_viento" != "kpigroup" ? (v.viento_int_viento ? v.viento_int_viento : 0) : 0);
                                        p.avg = ((p.sum ? p.sum : 0) / p.count);
                                        return p;
                                    },
                                    function (p, v) {
                                        --p.count;
                                        p.pct = (p.count / ndxSize) * 100;
                                        p.sum -= ("viento_int_viento" != "kpigroup" ? (v.viento_int_viento ? v.viento_int_viento : 0) : 0);
                                        p.avg = ((p.sum ? p.sum : 0) / p.count);
                                        return p;
                                    },
                                    function () {
                                        return {count: 0, pct: 0, sum: 0, avg: 0};
                                    }
                                );

    groupsline1[i] = tmpGroupline1.all().filter(function(d) { return d.key[1] == tmpSeriesline1; });

    lineChartsline1[i] = dc.lineChart(compositeChartline1)
                                .group(groupsline1[i], seriesline1[i])
                                .valueAccessor(function(d) {
                                    return parseFloat(d.value.avg);
                                })
                                .title(function(d) {
                                    var s = [];
                                    s.push(d.key[1] + ":");
                                    s.push("Conteo: " + (isNaN(d.value.count) ? "-" : d.value.count + " (" + d.value.pct.toFixed(2) + "%)"));
                                    if ("avg" != "count") {
                                        s.push("Media: " + (isNaN(d.value.avg) ? "-" : d.value.avg.toFixed(2) + ("avg" != "pct" ? "" : "%")));
                                    }
                                    return s.join("\n");
                                })
                                .colors(color[i])
                                .dashStyle([5,5]);
    }

    compositeChartline1
    .width(500).height(500)
    .margins({top: 60, right: 60, bottom: 120, left: 120})
    .x(d3.scaleOrdinal().domain(xRangeline1))
    .xUnits(dc.units.ordinal)
    .y(d3.scaleLinear().domain([0, yMaxline1]).range([500,0]))
    .xAxisLabel("X")
    .yAxisLabel("Y")
    .legend(dc.legend().x(40).y(20).itemHeight(seriesline1.length).gap(10))
    .dimension(dimensionline1)
    .renderHorizontalGridLines(true)
    .brushOn(false)
    .elasticY(true)
    .renderlet(function (chart) {
    chart.selectAll('g.x text').attr('transform', 'translate(-30,30) rotate(315)');
    })
    .compose(lineChartsline1);
}

Thanks in advance.


text:
Q: How to configure multiple django project running on different system ports using same IP with gunicorn This question is a bit lengthy, but I tried to provide as much information as possible from my doubts and trials. I've been fiddling with gunicorn and nginx configurations to host 3 django projects on an AWS EC2 ubuntu server. I've been unable to sort them to run, neither been able to fully understand the settings.
(1) First of all I have them them as follows (Each project folder has its own venv setup):
drwxrwxr-x 10 ubuntu ubuntu 4096 Mar 26 02:10 first_project/
drwxrwxr-x  7 ubuntu ubuntu 4096 Mar 26 01:20 second_project/
drwxrwxr-x  7 ubuntu ubuntu 4096 Mar 26 01:25 third_project/

(2) I tried creating separate .socket files in /etc/systemd/system/ folder
-rw-r--r--  1 root root  112 Mar 26 02:17  gunicorn_first.socket
-rw-r--r--  1 root root  112 Mar 26 02:19  gunicorn_second.socket
-rw-r--r--  1 root root  112 Mar 26 02:22  gunicorn_third.socket

(3) and included all of them with same content:
[Unit]
Description=gunicorn socket

[Socket]
ListenStream=/run/gunicorn.sock

[Install]
WantedBy=sockets.target

(4) Post adding .socket files, I added .service files
-rw-r--r--  1 root root  112 Mar 26 02:35  gunicorn_first.service
-rw-r--r--  1 root root  112 Mar 26 02:39  gunicorn_second.service
-rw-r--r--  1 root root  112 Mar 26 02:44  gunicorn_third.service

(5) and added content as follows (NTH  -> first , second, third)
[Unit]
Description=gunicorn daemon
Requires=gunicorn_NTH.socket
After=network.target

[Service]
User=ubuntu
WorkingDirectory=/home/ubuntu/NTH_project
ExecStart=/home/ubuntu/NTH_project/venv/bin/gunicorn --workers 3 --access-logfile - --bind unix:/run/gunicorn.sock NTH_project.wsgi:application

[Install]
WantedBy=multi-user.target

(6) And finally my nginx default configuration (/etc/nginx/sites-enabled/default) as follows. I've opened ports 8081, 8082, 8083 - one for each project
server {
    listen 8081;
    server_name MY_IP;

    location /first_project {
        root /home/ubuntu/first_project;
    }

    location / {
        include proxy_params;
        proxy_pass http://unix:/run/gunicorn_first.sock;
    }
}

server {
    listen 8082;
    server_name MY_IP;

    location /second_project {
        root /home/ubuntu/second_project;
    }

    location / {
        include proxy_params;
        proxy_pass http://unix:/run/gunicorn_second.sock;
    }
}

server {
    listen 8083;
    server_name MY_IP;

    location /third_project {
        root /home/ubuntu/third_project;
    }

    location / {
        include proxy_params;
        proxy_pass http://unix:/run/gunicorn_third.sock;
    }
}

The above approach doesn't work, so I replaced proxy_pass in each with http://unix:/run/gunicorn.sock -> and if I do so, only the last application (8083) is working, when I send requests to endpoint from postman (http://MY_IP:8083/some_endpoint). The other 2 are stating django error that the route is not found (404)
Can someone please help on how I can ensure all 3 apps are running
(http://MY_IP:8081/some1_endpoint)
(http://MY_IP:8082/some2_endpoint)
(http://MY_IP:8083/some3_endpoint)

If you can point which part(s) among 1-6 can be edited, it would be great
Thanks in advance.

A: You mentioned that gunicorn.sock works (for one of the sites). Was the socket and service configuration restarted after making the original changes and are all of the services running?
sudo systemctl restart <name>.socket
sudo systemctl restart <name>.service
sudo systemctl status <name>.service

Are these services accessible directly (i.e. when not using nginx as a proxy)? Consider modifying the gunicorn exec and review the error log.
ExecStart=/home/ubuntu/NTH_project/venv/bin/gunicorn --workers 3 --error-logfile /path/to/error.log ...

Once services are confirmed as accessible, check the nginx configuration for errors, ensuring that the proxy_params is in the expected location, or remove this line if problematic and enter any required proxy configuration directly.
sudo nginx -t

Once verified, restart nginx to re-establish the socket connection to Gunicorn and validate no further issues.
sudo systemctl restart nginx
sudo systemctl status nginx
tail var/log/nginx/error.log

redpajama_set_name: RedPajamaStackExchange


text:
Q: Doc4j pptx find and replace table row I have a requirement where I need to replace some text in a Powerpoint File at runtime(Powerpoint file is being used as a template with some placeholders/tokes e.g. {{data1}} ) in one row on table.
I referred to the other links on the forum and started with 'docx4j' but am not able to go beyond a point and the documentation is not very clear
    List tableCells = clonedRow.getTc();
    // Finally, insert the copy in the list
    theTable.getTr().add(clonedRow); // standard Java list API
     for (int ix = 0; ix < tableCells.size(); ix++)
     {
         CTTableCell  tableCell = (CTTableCell)XmlUtils.unwrap(tableCells.get(ix));
        // List<CTTextParagraph> value=tableCell.getTxBody().getP();

         for (CTTextParagraph p : tableCell.getTxBody().getP()) {
             Text text = (Text) ((JAXBElement) p).getValue();
            }

A: A SlidePart extends JaxbXmlPart, which contains:
public void variableReplace(java.util.Map<String, String> mappings)

If you want to use variableReplace, your variables should be appear like so: ${key1}, ${key2}
For an example, see https://github.com/plutext/docx4j/blob/master/src/samples/docx4j/org/docx4j/samples/VariableReplace.java  That's for a docx; you just need to apply it to your SlidePart.


text:
Q: Make all pages on domain go through specific page I am trying to get all pages on the domain, like on the domain example.com to go through a index.php without editing the url.  I can use htaccess and php.  For example, on the domain example.com I can go to example.com/thefile.php and it will still show the main file.

A: I figured it out by using the .htaccess for NamelessMC. The .htaccess file is:
Options +FollowSymLinks

Options -Indexes

RewriteEngine On

RewriteCond %{SCRIPT_FILENAME} !-d

RewriteCond %{SCRIPT_FILENAME} !-f

RewriteRule ^.*$ ./index.php


text:
Q: Thrift + ActiveMQ Integration My company is currently investigating the integration of Thrift and ActiveMQ. We'd like to set up a language-independant service layer that runs on a single http server, with each thrift service being able to communicate with other thrift services through ActiveMQ. I have been unable thus far to find anyone else who has tried to implement this. I'm curious as to how others might go about implementing this, and whether or not there is documentation on doing so.
The current prototype uses a simple python server that hosts various thrift services. Within each of the service calls (i.e., update a setting), an ActiveMQ message is created and sent to a particular queue (i.e., a settings service for one app sends out an update message to another). A service listener is created for each implementation of the settings service that is able to scan the appropriate queue and detect when a relevant message is sent over. This listener then uses Thrift to access the appropriate service for that particular application.
I'm trying to figure out a way to allow a service to serve a thrift object, but also receive ActiveMQ messages without the need to create these listeners, but I have been unable to find any resources for this.
Thanks!

A: From your description you have at least to options, IMHO:
(1) Make use of the serialization part and write the serialized messages into the queue. The listeners deserialize them and feed them to a (local) processor instance, which triggers the rest of the processing.
(2) Write a dedicated transport for it to support ActiveMQ. It may help to encapsulate the serialization/deserialization stuff better and provide the usual call interface to the clients/processors.
Two more tips:

*

*Have a look at THRIFT-812, which demonstrates the combination with ZeroMQ

*Have a look at the Thrift documentation for oneway methods. You'll find them quite useful for message queueing scenarios.

What do i mean by feeding incoming data into a local processor instance? Ok, here's a piece of code which I wrote some time ago to demonstrate that. It is written in Delphi, but should be simple enough to enable you to translate it into any other language of your choice. The request data are passed and expected as JSON in this particluar case, hence the JSON protocol.
class procedure TTextToolJsonServer.Process( const stmIn, stmOut : TStream);
var handler   : Samples.TTextTool.Iface;
    processor : IProcessor;
    protIn, protOut : IProtocol;
begin
  protIn  := TJSONProtocolImpl.Create(
               TStreamTransportImpl.Create(
                 TThriftStreamAdapterDelphi.Create( stmIn, FALSE), nil));

  protOut := TJSONProtocolImpl.Create(
               TStreamTransportImpl.Create(
                 nil, TThriftStreamAdapterDelphi.Create( stmOut, FALSE)));

  handler   := TTextToolHandler.Create;
  processor := Samples.TTextTool.TProcessorImpl.Create( handler);
  processor.Process( protIn, protOut);
end;


text:
Q: ¿Como muestro un mensaje de 'No hay resultados'? Tengo un filtro de preguntas en tiempo real con JQuery, funciona a la perfección, pero cuando no haya resultados de la busqueda necesito añadir un mesaje que lo diga, ej. 'No hay resultados para tu pregunta'
¿Como puedo hacerlo?

.hidden {display:none;}

<input type="text" id="search-project" name="search-project" placeholder="intenta: ¿Como hago mi primera compra?">

¿Como puedo fíar un producto?

¿Puedo vender mis productos?

¿Que se puede vender?

¿Existe la posibilidad de comprar sin tarjeta?

A: Puedes crear el mensaje en el html y tenerlo oculto por defecto. Y mostrarlo cuando no hay ninguna coincidencia.
He creado una variable local para saber si ha habido alguna coincidencia o no. Y siempre compruebo si el mensaje es visible pues se oculta.

.hidden {display:none;}

<input type="text" id="search-project" name="search-project" placeholder="intenta: ¿Como hago mi primera compra?">

No hay resultados

¿Como puedo fíar un producto?

¿Puedo vender mis productos?

¿Que se puede vender?

¿Existe la posibilidad de comprar sin tarjeta?

A: Hola pues esta ha sido mi solución, verás he creado un elemento párrafo que le he puesto la clase hidden también.
Luego cuando añades la clase hidden a los elementos de la lista vuelvo a recorrer los elementos li y sumo 1 a una variable contador. Una vez termina de recorrer sale y compara el contador con los elementos li que existen y si contador es mayor muestro el mensaje.

(function($) {
  $(document).ready(function() {
    let contador = 0;
    let elementos = $(".list-porject li");
    $("#search-project").keyup(function() {
      var filter = $(this).val();
      $(".list-porject li").each(function() {
        if ($(this).text().search(new RegExp(filter, "i")) < 0) {
          $(this).addClass('hidden');
          $(".list-porject li").each(function() { //vuelvo a recorrer los li
            if ($(this).hasClass('hidden')) { // si un elemento tiene la clase hidden
              contador++; //le sumo 1 a contador
            }
          });
          if (contador >= elementos.length) { //si contador es mayor o igual que los elementos li existentes
            $('.vacio').css('display', 'block'); //aplico el estilo es decir hago visible el parrafo con el mensaje
          }
        } else {
          $(this).removeClass('hidden');
        }
      });

    });
  })
})(jQuery)
.hidden,
.vacio {
  display: none;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

<input type="text" id="search-project" name="search-project" placeholder="intenta: ¿Como hago mi primera compra?">

¿Como puedo fíar un producto?

¿Puedo vender mis productos?

¿Que se puede vender?

¿Existe la posibilidad de comprar sin tarjeta?

No hay resultados.

Espero te sirva.

A: Podrías crear un elemento donde tener el mensaje No hay resultados.. Luego, dependiendo si la cantidad de li es igual a la cantidad de li.hidden, entonces habria que mostrar dicho elemento.
Ejemplo:

(function($) {
  $(function() {
    $("#search-project").keyup(function() {

      // Retrieve the input field text and reset the count to zero
      var filter = $(this).val();
      var regEx = new RegExp(filter, "i");

      // Loop through the comment list
      $(".list-porject li").each(function() {
        let contains = $(this).text().search(regEx) >= 0;

        // If the list item does not contain the text phrase fade it out
        $(this)[contains ? 'removeClass' : 'addClass']('hidden');
      });

      // If all nodes are hidden
      let empty = $(".list-porject li").length == $(".list-porject li.hidden").length;
      $('.empty')[empty ? 'removeClass' : 'addClass']('hidden');
    });
  })
})(jQuery)
.hidden {
  display: none;
}

<input type="text" id="search-project" name="search-project" placeholder="intenta: ¿Como hago mi primera compra?">

¿Como puedo fíar un producto?

¿Puedo vender mis productos?

¿Que se puede vender?

¿Existe la posibilidad de comprar sin tarjeta?

No hay resultados.


text:
Q: WebP is pixelated I'm struggling with a problem with pixelated images. I downloaded the logo of Amazon(PNG) then I moved it to my Android project files and converted it to WebP. The problem is that image it's pixelated.
Image(
    painter = painterResource(id = R.drawable.amazon),
    contentDescription = "",
    modifier = Modifier
        .align(Alignment.Center)
        .matchParentSize()
        .scale(3F, 3F),
    contentScale = ContentScale.Fit
)

I tried downloading images in SVG format and convert to XML but it doesn't work at all.
What should I do to display a clear image?


text:
Q: Select takes long time. How to solve this problem? I have a big base in MYSQL - 300 mb, where are 4 tables: the first one is about 200mb, the second is - 80.
There are 150 000 records in first table and 200 000 in second.
At the same time I use inner join there.
Select takes 3 seconds when I use optimization and indeces (before that it took about 20-30 seconds).
It is enough good result. But I need more, because page is loading for 7-8 seconds (3-4 for select, 1 for count, another small queries 1 sec, and 1-2 for page generation).
So, what I should do then? May be postgres takes less time than mysql? Or may be better to use memcaches, but in this case it can take lots of memory then (there are too many variants of sorting).
May be anybody has another idea? I would be glad to hear the new one:)

OK. I see we need queries:)
I renamed fields for table_1.
     CREATE TABLE  `table_1` (
      `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
      `field` varchar(2048) DEFAULT NULL,
      `field` varchar(2048) DEFAULT NULL,
      `field` int(10) unsigned DEFAULT NULL,
      `field` text,
      `field` text,
      `field` text,
      `field` varchar(128) DEFAULT NULL,
      `field` text,
      `field` text,
      `field` text,
      `field` text,
      `field` text,
      `field` varchar(128) DEFAULT NULL,
      `field` text,
      `field` varchar(4000) DEFAULT NULL,
      `field` varchar(4000) DEFAULT NULL,
      `field` int(10) unsigned DEFAULT '1',
      `field` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
      `field` text,
      `new` tinyint(1) NOT NULL DEFAULT '0',
      `applications` varchar(255) DEFAULT NULL,
      PRIMARY KEY (`id`),
      KEY `indexNA` (`new`,`applications`) USING BTREE
    ) ENGINE=InnoDB AUTO_INCREMENT=153235 DEFAULT CHARSET=utf8;

CREATE TABLE  `table_2` (
  `id_record` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `catalog_name` varchar(512) NOT NULL,
  `catalog_url` varchar(4000) NOT NULL,
  `parent_id` int(10) unsigned NOT NULL DEFAULT '0',
  `checked` tinyint(1) NOT NULL DEFAULT '0',
  `level` int(10) unsigned NOT NULL DEFAULT '0',
  `work` int(10) unsigned NOT NULL DEFAULT '0',
  `update` int(10) unsigned NOT NULL DEFAULT '1',
  `type` int(10) unsigned NOT NULL DEFAULT '0',
  `hierarchy` varchar(512) DEFAULT NULL,
  `synt` tinyint(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id_record`,`type`) USING BTREE,
  KEY `rec` (`id_record`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=14504 DEFAULT CHARSET=utf8;

CREATE TABLE  `table_3` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `id_table_1` int(10) unsigned NOT NULL,
  `id_category` int(10) unsigned NOT NULL,
  `work` int(10) unsigned NOT NULL DEFAULT '1',
  `update` int(10) unsigned NOT NULL DEFAULT '1',
  PRIMARY KEY (`id`),
  KEY `site` (`id_table_1`,`id_category`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=203844 DEFAULT CHARSET=utf8;

There queries are:
1) get general count (takes less than 1 sec):
SELECT count(table_1.id) FROM table_1
 INNER JOIN table_3 ON table_3.id_table_id = table_1.id
 INNER JOIN table_2 ON table_2.id_record = table_3.id_category
WHERE ((table_2.type = 0)
AND (table_3.work = 1 AND table_2.work = 1)
 AND (table_1.new = 1))AND 1 IN (table_1.applications)

2) get list for page with limit (it takes from 3 to 7 seconds, depends on count):
SELECT table_1.field, table_1.field, table_1.field, table_1.field, table_2.catalog_name FROM table_1
 INNER JOIN table_3 ON table_3.id_table_id = table_1.id
 INNER JOIN table_2 ON table_2.id_record = table_3.id_category
WHERE ((table_2.type = 0)
AND (table_3.work = 1 AND table_2.work = 1)
 AND (table_1.new = 1))AND 1 IN (table_1.applications) LIMIT 10 OFFSET 10

A: Do Not Change DBMS
I would not suggest to change your DBMS, it may be very disruptive. If you have used MySQL specific queries that are not compatible with Postgres; you might need to redo whole indexing etc. Even then it may not guarantee a performance improvement.
Caching is a Good Option
Caching is really good idea. It takes load off your DBMS. It is best suited if you have heavy read, light write. This way objects would stay more time in Cache. MemcacheD is really good caching mechanism, and is really simple. Rapidly scaling sites (like Facebook and the likes) make heavy use of MemcacheD to alleviate the load from database.
How to Scale-up Really Big Time
Although, you do not have very heavy data.. so most likely caching would help you. But the next step ahead of caching is noSQL based solutions like Cassandra. We use cassandra in one of our application where we have heavy read and write (50:50) operation and database is really large and fast growing. Cassandra gives good performance. But, I guess in your case, Cassandra is an overkill.
But...
Before, you dive into any serious changes, I would suggest to really look into indexes. Try scaling vertically. Look into slow queries. (Search for slow query logging directive). Hopefully, MySQL will be faster after optimizing these thing and you would not need additional tools.

A: You should look into indexing specific to the most frequent/time consuming queries you use. Check this post on indexing for mysql.

A: Aside from all the other suggestions others have offered, I've slightly altered and not positive of the performance impact under MySQL.  However, I've added STRAIGHT_JOIN so the optimizer doesn't try to think which order or table to join FOR you.
Next, I moved the "AND" conditions into the respective JOIN clauses for tables 2 & 3.
Finally, the join from table 1 to 3 had (in your post)
   table_3.id_table_id = table_1.id

instead of
   table_3.id_table_1 = table_1.id

Additionally, I can't tell performance, but maybe having a stand-alone index on just the "new" column for exact match first without regards to the "applications" column.  I don't know if the compound index is causing an issue since you are using an "IN" for the applications and not truly an indexable search basis.
Here's the modified results
SELECT STRAIGHT_JOIN
        count(table_1.id)
    FROM
        table_1
            JOIN table_3
                ON table_1.id = table_3.id_table_1
                   AND table_3.work = 1
                JOIN table_2
                    ON table_3.id_category = table_2.id_record
                    AND table_2.type = 0
                    AND table_2.work = 1
    WHERE
            table_1.new = 1
        AND 1 IN table_1.applications

SELECT STRAIGHT_JOIN
        table_1.field,
        table_1.field,
        table_1.field,
        table_1.field,
        table_2.catalog_name
    FROM
        table_1
            JOIN table_3
                ON table_1.id = table_3.id_table_1
                AND table_3.work = 1
                JOIN table_2
                    ON table_3.id_category = table_2.id_record
                    AND table_2.type = 0
                    AND table_2.work = 1
    WHERE
            table_1.new = 1
        AND 1 IN table_1.applications
    LIMIT 10 OFFSET 10

A: You should also optimize your query.

A: Without a look into the statements this question can only be answered using theoretical approaches. Just a few ideas to take into consideration...
The SELECT-Statement...
First of all, make sure that your query is as "good" as it can be. Are there any indeces you might have missed? Are those indeces the same field types and so on? Can you perhaps narrow the query down so the database has less to work on?
The Query cache...
If your query is repeated pretty often, it might help to use the Query cache or - in case you're already using it - give it more RAM.
The Hardware...
Of course different RDBMS are slower or faster than others, depending on their strenght or weaknesses, but if your query is optimized into oblivion, you only can get it faster while scaling up the database server (better cpu, better i/o and so on, depending on where the bottleneck is).
Other Factors...
If this all is maxed out, maybe try speeding up the other components (1-2 secs for page generation looks pretty slow to me).
To all those factors mentioned there is a huge amount of ideas and posts in stackoverflow.com.

A: That is actually not such a big database, certainly not too much for your database system. As comparison, the database that we are using is currently around 40 GB. It's an MS SQL Server, though, so it's not directly comparable, but there is no dramatic difference between the database systems.
My guess is that you haven't been completely successful in using indexes to speed up the query. You should look at the execution plan for the query and see if you can spot what part of the execution that is taking most of the time.


text:
Q: Disable Tap Gesture on Child View Controller? How to determine Is it a PanGesture or TapGesture? All.
In my iOS 8.0 app.
In a Parent Child View architecture. By this code...
[self addChildViewController:slideTableViewController];
[self.view addSubview:slideTableViewController.view];
[slideTableViewController didMoveToParentViewController:self];

I have implemented TapGesturerecognizer & PanGesturerecognizer on Base View Controller.
So, that it can recognise Pan(Dragging) and Tap. I need both gestures on my BaseView.
Just do not want Tap Gesture on SlideView.
As I want to execute didSelectRowAtIndexpath method on child view,
Solution:
Answer for Question 1:
Many StackOverflow answers have the same funda..
Disable Tap gesture when your touch encounters child view.
if([gestureRecognizer isKindOfClass:[UITapGestureRecognizer class]]){
                if(CGRectContainsPoint(slideTableViewController.view.frame,[touch locationInView:self.view])){
                    return NO;
     }
}

Answer for Question 2:
How to determine Is it a PanGesture or TapGesture ?
For each gesture type the delegate method will call
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch

If you have implemented two gestures in your view, pan gesture and touch gesture,
This method will call 2 times, 1 time for pan gesture and 1 time for tap gesture.
So, in this method you can check like isKindOfClass method.
Thank you very much for helping......

A: Just set tapGesture.cancelsTouchesInView = YES;

A: You can implement the gesture's delegate method in your baseViewController :
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizershouldReceiveTouch:(UITouch *)touch {
    return touch.view == self.view;
}

OR
//If it is a Tap Gesture and Your touch intersects with a perticular View, For that we have this method.
if([gestureRecognizer isKindOfClass:[UITapGestureRecognizer class]]){
                if(CGRectContainsPoint(slideTableViewController.view.frame,[touch locationInView:self.view])){
                    return NO;
     }
}

A: I have done this in UIViews I hope this could help you:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{

UITouch *touch = [touches anyObject];
[touch locationInView:self.view];
if(touch.view == self.topView )
{
     //just return
}
if(touch.view == SOSTopView )
{
   //just return
}
}

A: Looks like you should implement this method of UITableViewDelegate:
- (NSIndexPath *)tableView:(UITableView *)tableView
  willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // you can add some logic here
    return nil;
}

This will prevent from selecting any rows.

A: Isn't there a userInteractionEnabled property that you can make use of? So you could do the following:
slideTableViewController.userInterationEnabled = NO;


text:
Q: Using hardware through webpage So, I am trying  to make a web page that, after the button for Memory game is clicked it will do two things:

*

*It will set the cloud function I wrote in the hardware's code and act accordingly and

*It will go to another web page entirely.

However, when I try to make it do this, it doesn't work. I am not sure if the hardware is even getting the correct message (haven't tested it yet) but I should be able to go to the next page. Through testing, it goes to the next page if the $.post( requestURL, { params: thisGame, access_token: accessToken }); is commented out.
Please, any assistance is much appreciated
<!DOCTYPE html>
<html>
    <body>
        <input id="Memory Button" type="button" value="Memory Game" onclick="myFunction1('Memory')"/>

        <script language="javascript" type="text/javascript">

            var deviceID = "device id";
            var accessToken = "access token";
            var baseURL = "https://api.particle.io/v1/devices/";
            var whichGame="setGame";

            function myFunction1(thisGame)
            {
                var requestURL = "https://api.spark.io/v1/devices/" + deviceID + "/" +   whichGame + "/?access_token=" + accessToken;

                $.post( requestURL, { params: thisGame, access_token: accessToken });

                myFunction2();
            }

            function myFunction2()
            {
                window.location.href = 'http://twin-cities.umn.edu/';
            }

        </script>
    </body>
</html>

A: Include the jquery cdn in the header like this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

And you may try using AJAX with the following code:
var ajax = $.ajax({
        url: yourURL,
        data: data,
        type: 'POST',
        beforeSend : function(xhr) {
            xhr.setRequestHeader("token", token_value);         //append token to header
        },
        error : function(response){                     //if something went wrong on server
            console.log(response);
            alert("Something went wrong. Please try later.");
        },
        success: function(response){
            //call the function you wanted to call here
        }
    });

Where 'data' is a stringified object containing all the data you want to send.

A: Change:
function myFunction1(thisGame)
{
    var requestURL = "https://api.spark.io/v1/devices/" + deviceID + "/" +   whichGame + "/?access_token=" + accessToken;

    $.post( requestURL, { params: thisGame, access_token: accessToken });
      myFunction2();
}

to:
function myFunction1(thisGame)
{
    var requestURL = "https://api.spark.io/v1/devices/" + deviceID + "/" +   whichGame + "/?access_token=" + accessToken;

    $.post( requestURL, { params: thisGame, access_token: accessToken })
      .done(myFunction2)
      .fail(function(){ alert('FAIL!'); });
}

And add this just after the <html> tag:
<head>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js'></script>
</head>


text:
Q: Efficient way to fill up a 4d array from entries of a product of two matrices Title might be not as precise than I hoped, but here is the problem. Basically I'm filling a 4d numpy array from the entries of the product of two matrices. Right now the code is the following :
M = P.dot(U)
C_arr = np.zeros((b_size,b_size,N,N))
  for alpha in xrange(b_size):
      for beta in xrange(b_size):
          for i in xrange(N):
              for j in xrange(N):
                  C_arr[alpha,beta,i,j] = np.conjugate(M[i,alpha])*M[j,beta]

It turns out that this function is called quite ofen and appears to be very time-consumming. I'm just beginning with Python and I suspect that there could be a more efficient way to write this function by avoiding those loops, but haven't been able to figure it out by myself...

A: You can use numpy.einsum:
C = np.einsum('ia,jb->abij', M.conj(), M)

Or, since there is no actual sum being computed (i.e. this is a form of an outer product), you can use numpy broadcasting with regular array multiplication after reshaping the input matrix M appropriately:
nrows, ncols = M.shape
C = M.T.reshape(1, ncols, 1, nrows) * M.T.conj().reshape(ncols, 1, nrows, 1)

A: Apart from the terse code with np.einsum listed in the other solution, you can also use outer-product with np.outer like so -
np.outer(M.conj().ravel(),M.ravel()).reshape(N,b_size,N,b_size).transpose(1,3,0,2)

Runtime tests -
In [54]: # Create input and get shape parameters
    ...: M = np.random.rand(10,10)
    ...: N,b_size = M.shape
    ...:

In [55]: %timeit np.einsum('ia,jb->abij', M.conj(), M)
10000 loops, best of 3: 26 µs per loop

In [56]: %timeit np.outer(M.conj().ravel(),M.ravel()).reshape(N,b_size,N,b_size).transpose(1,3,0,2)
10000 loops, best of 3: 55.6 µs per loop

In [57]: # Create input and get shape parameters
    ...: M = np.random.rand(40,40)
    ...: N,b_size = M.shape
    ...:

In [58]: %timeit np.einsum('ia,jb->abij', M.conj(), M)
10 loops, best of 3: 31 ms per loop

In [59]: %timeit np.outer(M.conj().ravel(),M.ravel()).reshape(N,b_size,N,b_size).transpose(1,3,0,2)
10 loops, best of 3: 24.2 ms per loop

In [60]: # Create input and get shape parameters
    ...: M = np.random.rand(80,80)
    ...: N,b_size = M.shape
    ...:

In [61]: %timeit np.einsum('ia,jb->abij', M.conj(), M)
1 loops, best of 3: 497 ms per loop

In [62]: %timeit np.outer(M.conj().ravel(),M.ravel()).reshape(N,b_size,N,b_size).transpose(1,3,0,2)
1 loops, best of 3: 399 ms per loop

Thus, depending on the shape of the input array, you can go either way.


text:
Q: HttpHandler expiration for PivotViewer I have been trying to get my PivotViewer implementation to NOT cache the HttpResponse but have not been successful. How does one set the expiration of a Response object? I have been doing the following.
           _HttpContext.Response.Expires = 0;
           _HttpContext.Response.ExpiresAbsolute = DateTime.Now.Subtract( new TimeSpan( 1, 0, 0, 0 ) );
           _HttpContext.Response.CacheControl = "no-cache";

The problem is - subsequent call to display my PivotViewer always display the results of the first call. I am not using a static CXML - I am using the PivotServer tools and creating it dynamically.
What I want to know is how to set the expiry of the page so that each Pivot View request creates a HttpResponse or has the PivotViewer got a bug in it and it is ignoring cache control?

A: I am assuming that you are making multiple LoadCollection() calls to the same URL and wondering why you are not getting a refresh, correct?  If that's not the case then I misunderstood.
The PivotViewer will not make a new call if the Uri string passed in the LoadCollection() is identical to the previous call.  Even adding a hash tag will not trick it.  I'm not sure if this is a performance thing or what, but it is what it is.  The only real way to reload the collection is to change the Uri.  I typically do this by adding/modifying a querystring counter.
I have an example of this in a blog post : Reloading a Collection in PivotViewer
If you are having a different problem please let me know and we can get you fixed up.


text:
Q: Spring specification with subquery, union, join and case statements I have very long and complex queries, I am using spring data,
can someone please help me to achieve below query in spring jpa, I can't use native query as spring is not supporting parameter injection in subqueries.
select desc as desc, priority as priority, activeUser as activeUser,
totalUser as totalUser
 from
(
  select stat.desc as desc,
  stat.priority as priority,
  (case when sum(activeUser) is null then 0 else sum(activeUser) end) as
  activeUser,
   (case when sum(totalUser) is null then 0 else sum(totalUser) end) as
  totalUser
  from lookup.user stat left outer join
  (
  select user.role as role,
  sum (case when user.STATUS = 'ACTIVE' then 1 else 0 end) as activeUser,
  count(*) as totalUser,
  user.group as group
  from ctrl.user user
  where user.group =:userGroup
  and user.branch_code =:branchCode
  group by user.role,user.group
  ) as tbl on stat.role = tbl.role and stat.group = tbl.group
  where stat.group =:userGroup
  group by stat.desc, stat.priority
 union
 select 'Total' as desc,
 '999' as priority,
   (case when sum(activeUser) is null then 0 else sum(activeUser) end) as
    activeUser,
   (case wh en sum(totalUser) is null then 0 else sum(totalUser) end) as
   totalUser
  from lookup.user stat left outer join
   (
  select user.role as role,
  sum (case when user.STATUS = 'ACTIVE' then 1 else 0 end) as activeUser,
    count(*) as totalUser,
   user.group as group
   from ctrl.user user
   where user.group =:userGroup
   and user.branch_code =:branchCode
   group by user.role,user.group
   ) as tbl on stat.role = tbl.role and stat.group = tbl.group
   where stat.group =:userGroup
    ) as tblMain order by priority

I have tried to generate predicate as below but its not taking selects
  Specification<CtrlUser> sp= new Specification<CtrlUser>() {

        @Override
        public Predicate toPredicate(Root<CtrlUser> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
            // TODO Auto-generated method stub

            query.multiselect(root.get("role"), cb.selectCase().when(root.get("status").in("ACTIVE"), 1).otherwise(0).alias("ActiveUsers"),
                    cb.count(root).alias("totalUsers"),root.get("group")).groupBy(root.get("role"),root.get("group"));
            return cb.and(cb.equal(root.get("branchCode"), branchCode), cb.equal(root.get("group"), userGroup));
        }
    };

I have searched online, but not much of luck.
if require more info, please let me know.


text:
Q: How to use correctly tridimensional arrays to save and print strings? I have to save three different strings in n number of 2D arrays, for that reason I created a 3D array named datosCliente[size][4][size]. After that I have to print their content. But when I'm printing the strings in the first and second string the first character disappear, and the third string isn't printed.

The first string is the name of a country.
The second is the date of departure.
The last is the date of return.

This is the code:
#include <stdio.h>
#include <stdlib.h>

const int size = 100;

void ingresoDatos(char [size][4][size], int*);
void imprimirDatos(char [size][4][size], int*);

int main(void) {
  char  datosCliente[size][4][size];
  int cant;
  FILE *document;
  document = fopen("data.txt", "a");
  if(document == NULL) {
    printf("Error al abrir el archivo.\n");
  }else {
    ingresoDatos(datosCliente, &cant);
    imprimirDatos(datosCliente, &cant);
  }
  fclose(document);
  return 0;
}

void ingresoDatos(char datos[size][4][size], int *cant) {
  int tam = 0;
  system("clear");
  printf("Ingreso de datos\n");
  do {
    printf("Ingrese el número de clientes: ");
    scanf("%d", &tam);
  }while(tam >= 100 || tam <= 0);
  *cant = tam;
  for(int i = 1; i <= tam; i++) {
    system("clear");
    printf("Ingrese el destino: ");
    fgets(&datos[i][0][0], 20, stdin);
    getchar();
    printf("Ingrese la fecha de salida: ");
    fgets(&datos[i][1][0], 30, stdin);
    getchar();
    printf("Ingrese la fecha regreso: ");
    fgets(&datos[i][2][0], 30, stdin);
    getchar();
  }
}
void imprimirDatos(char datos[size][4][size], int *cant) {
  system("clear");
  for(int i = 1; i <= *cant; i++) {
    printf("Cliente %d:\n", i+1);
    printf("Destino: %s", &datos[i][0][100]);
    printf("Fecha de salida: %s", &datos[i][1][100]);
    printf("Fecha de regreso: %s", &datos[i][2][100]);
    printf("\n");
  }
}

I enter this data:
tam: 1
Destino (to): China
Fecha de salida (depart in): 23 de septiembre de 2022
Fecha de regreso (return in): 24 de noviembre de 2022

And this is the output:
Cliente 1:
Destino: hina
Fecha de salida: 3 de septiembre de 2022
Fecha de regreso:

I had forgotten mention but I'm using Replit to do the code.

A: *

*scanf("%d", &tam); doesn't consume a newline character even if it is entered. (c - fgets doesn't work after scanf - Stack Overflow) In my opinion, you shouldn't mix scanf() and fgets(). You can use fgets() to read a line and sscanf() to parse the line.

*fgets() consumes a newline character (if it is entered). Calling getchar(); after that will drop the first character of the next line.

Considering these points, the function ingresoDatos should be:
void ingresoDatos(char datos[size][4][size], int *cant) {
  int tam = 0;
  system("clear");
  printf("Ingreso de datos\n");
  do {
    char buffer[100];
    printf("Ingrese el número de clientes: ");
    fgets(buffer, sizeof(buffer), stdin);
    sscanf(buffer, "%d", &tam);
  }while(tam >= 100 || tam <= 0);
  *cant = tam;
  for(int i = 1; i <= tam; i++) {
    system("clear");
    printf("Ingrese el destino: ");
    fgets(&datos[i][0][0], 20, stdin);
    printf("Ingrese la fecha de salida: ");
    fgets(&datos[i][1][0], 30, stdin);
    printf("Ingrese la fecha regreso: ");
    fgets(&datos[i][2][0], 30, stdin);
  }
}


text:
Q: Creating File in other pc Connected to Lan using java I am trying to Create a txt file using java in other pc and i am trying to doing code is.
try {
            File f = new File("sftp://ip/home/username/krish.txt");

            boolean check = f.createNewFile();
            if (check) {
                System.out.println("File Created!!!");
                return true;
            }
            else{
                System.out.println("File not Created!!!");
                return false;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

what i am getting error is :
java.io.IOException: No such file or directory
    at java.io.UnixFileSystem.createFileExclusively(Native Method)
    at java.io.File.createNewFile(File.java:959)

can any body suggest solution?

A: To manage file that are in a remote machine you will use a network communication protocol. in your case  you are trying to use Secure FTP , so you have to use a Java API that handle this job . try JSch
 it may help you.


text:
Q: i3 Screen Brightness Control using light So i have recently started using i3 on my arch install. slowly i setup my config files with keybinds and all. About 2 days ago i install light ( to control screen brightness ) and it was working fine. but now suddenly i noticed that pressing the brightness keys did nothing. after trying the command light -S 100 in the terminal nothing happend. then i ran it as sudo and it worked. because the command suddenly needs to be run as sudo my keybind wont work.
my keybinds for brightness control in my i3 config files are:
bindsym XF86MonBrightnessDown exec sudo light -U 10
bindsym XF86MonBrightnessUp exec sudo light -A 10

is there anyway i can make light work without sudo?
or im i stuck with using light as sudo in the terminal to control my screen brightness?

A: You could use the desrcibed way of adding yourself to the video group as explained here .
Or you can set the SUID bit by doing
sudo chmod +s /usr/bin/light
which wont require you to type sudo password everytime. Also you could set a keyboard binding to go with this.
Hope this helps.

A: Add yourself to the video group.
sudo usermod -a -G video username


text:
Q: Ruby 1.9 performance issue with Array#flatten I have two questions regarding the performance of the Array#flatten method.
Below is a simple test comparing the flatten method to a home-made naive implementation with Enumerable#inject.
a) How can my inject code perform significantly better than the native flatten implementation - and I am using the flatten(1) version
b) What is the spike in time observed every 10 or so lines in the test - could this be a garbage collecting effect?
array = (1..3).collect {(1..100).to_a}
30.times {100.times {array.flatten(1)}}
30.times {100.times {array.inject([]) {|a, e| a += e}}}

with a formatted tracking code
30.times {now = Time.now; 100.times {array.flatten(1)};                 p "#{(1000 * (Time.now - now)).to_i.to_s.rjust(4)}ms"}
30.times {now = Time.now; 100.times {array.inject([]) {|a, e| a += e}}; p "#{(1000 * (Time.now - now)).to_i.to_s.rjust(4)}ms"}

I've tried this in plain irb and also a Rails script/console environment with the same results.  The inject version outperforms significantly the Array#flatten method.


text:
Q: How to get rid of "No jax-rs activator is defined for the project" warning? I have a web project in my eclipse workspace, and I'm getting this annoying warning:
No jax-rs activator is defined for the project
I know that this is related to web-services, but I currently don't use web services on this project.

A: The easiest way is to just make Eclipse shut up about it.
Go to the Preferences of your project > JAX-RS Validator > JAX-RS Validator > check Enable project specific preferences  and then JAX-RS Activators > set No JAX-RS Activator configured to Ignored.
Hope this helps.

A: For me (JBoss Developer Studio 7.1.1 GA) it was:
right-click project in Package Explorer --> Properties --> Jax-RS Validator
--> uncheck JAX RS support:


text:
Q: WebStorm debugging create-react-native-app What should I set in Run Debug Configuration in WebStorm to debug a app created by create-react-native-app?

I'm at a loss on how to debug since it doesn't use ~/.node_modules/lib/node_modules/react-native-cli but a custom module called react-native-scripts to start the compiling:
package.json:
 "main": "./node_modules/react-native-scripts/build/bin/crna-entry.js",
  "scripts": {
    "start": "react-native-scripts start",
    "eject": "react-native-scripts eject",
    "android": "react-native-scripts android",
    "ios": "react-native-scripts ios",
    "test": "node node_modules/jest/bin/jest.js --watch",
    "menu": "adb shell input keyevent 82"
  },

A: You have to use Webstorm/Intellij 2018.1 (through EAP at the moment)
https://youtrack.jetbrains.com/issue/WEB-26951
https://blog.jetbrains.com/webstorm/2018/02/webstorm-2018-1-eap-181-3263/#debugging-expo

A: I dont think you can do this, at least not in an easy way, and why would you wan't to do it anyway?
React Native ships with great debugging capabilities "out of the box" via Chrome Developer Tools.
Here you can debug code, both running on emulators, and even better on a real device.
See here for details: https://facebook.github.io/react-native/docs/debugging.html


text:
Q: C++ iterator operator precedence issue *it.method() vs (*it).method() vs it->method() This code won't compile:
for(vector<Box>::iterator it = shapes.end(); it >= shapes.begin(); --it){
    *it.update(1,1);
    *it.draw();
}

It claims:
main.cpp:80:17: error: 'std::vector<Box>::iterator' has no member named 'update'
main.cpp:81:17: error: 'std::vector<Box>::iterator' has no member named 'draw'

However AFAIK, that code doesn't try and call vector::iterator.draw(), it dereferences the iterator, which should give me an object of my class box, which does have those methods.
What am I doing wrong, and sorry for the awful title.

A: It's a matter of operator precedence.
Operator . has higher precedence than operator *. Use parenthesis to force operator * application first.
(*it).update(1,1);
(*it).draw();

You can also use operator -> on iterators.
it->update(1,1);
it->draw();

Also see: What is the difference between the dot (.) operator and -> in C++? and cppreference: Member access operators.

@andre stated correctly that you can also use reverse iterators to iterate over a sequence in reverse order but you should use them correctly.

for(vector<Box>::reverse_iterator it = shapes.rbegin(); it != shapes.rend(); ++it)
{
  it->update(1,1);
  it->draw();
}

A: also, to add on @Pixelchemist 's answer.
for(vector<Box>::iterator it = shapes.end(); it >= shapes.begin(); --it){
    *it.update(1,1);
    *it.draw();
}

should be:
for(vector<Box>::reverse_iterator it = shapes.rbegin(); it != shapes.rend(); ++it){
    *it.update(1,1);
    *it.draw();
}

rend and rbeing are used to iterate in reverse.


text:
Q: Python XPath from URL returning empty list I am trying to access an element of the following URL using XPath:
http://www.booking.com/searchresults.html?dest_id=2400&dest_type=region&offset=288
The specific element I am looking for is the Div class "sr_item_link_to_villas ".  I have been using the following XPath to trying to access it (in this example I am trying to access the second listing, but the full script loops through each listing), but it returns an empty list:
//*[@id="hotellist_inner"]/*[contains(@class,"sr_item")][2]//*[contains(@class,"sr_item_link_to_villas ")]

The full code is:
url='http://www.booking.com/searchresults.html?dest_id=2400&dest_type=region&offset=288'
page = parse(url).getroot()
pathstr='//*[@id="hotellist_inner"]/*[contains(@class,"sr_item")][2]//*[contains(@class,"sr_item_link_to_villas ")]'
content=page.xpath(pathstr)

A: Following Code may solve your purpose. You have to add header value for get data.
    import urllib2
    from lxml import etree
    from lxml.html import tostring,fromstring

    def get_HTML(url):
        header={"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:41.0) Gecko/20100101 Firefox/41.0","Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8","Connection": "keep-alive"}
        req=urllib2.Request(url,None,header)
        return urllib2.urlopen(req).read()

    url="http://www.booking.com/searchresults.html?dest_id=2400&dest_type=region&offset=288"

    read = get_HTML(url)
    tree = etree.HTML(read)
    data = tree.xpath("//div[@class='sr_item_link_to_villas ']/a/text()");
    print data


text:
Q: Does anyone know this Resistor Code? Hey everyone I am recently trying to map out a faulty circuit board on LTSpice and have come to a grinding stop. there is a resistor that I honestly cannot decifer the code for and sadly my multimeter is on the fritz..... I am attaching a picture of the resistor for reference, any help would be greatly appreciated!]1

A: brown-black-green: I'd say 1MΩ.


text:
Q: "in the plate" or "on the plate" I am learning English with Duolingo.
One example sentence is:

The forks are on the plates.

Another one is:

I have her fork in my plate.

What's the difference between "in the plate" and "on the plate"?

A: The literal sense is...

plate - a shallow, usually circular dish, often of earthenware or porcelain, from which food is eaten.

It's not always possible to classify any given item as a plate or a bowl, but the general principle is that plates are flat surfaces, so food (or anything else) goes on them. In contrast, bowls are (also usually circular) containers with raised sides - capable of holding liquids such as soup, which goes in them.
Thus OP's example usage #1 is what we would normally expect when describing the spatial relationship between the forks and the plates.

But note the figurative sense #2 in my link - the contents of such a dish; plateful, and consider this

"Someday, I hope you'll mean that," she replied, sticking her fork in his plate for a quick taste.

As a native speaker, my natural inclination is to interpret OP's second example in terms of that second definition (she sticks her fork into the food on his plate, in order to help herself to some of it).

TL;DR: Things are usually located on plates (including the figurative "I had too much on my plate already to take on another task" as per the idiomatic sense 34 in my link above). Usages such as "Lindsey stopped eating and set her fork in her plate." are relatively uncommon, so native speakers may well look for an alternative interpretation to explain/justify the unusual preposition.

A: I think that, over the past few years at least, plates have become less flat, that is, with more elevated sides.  Maybe because of the variety of cuisines--more liquids for example--a deeper plate has been desirable. The top outside edge of our white plates at home is 1" above the bottom edge, for example.  That's not flat, not like our heavy brown dishes.  That's enough for me to start to think of food as being in the white plates but still on the brown ones.  So the more that plates resemble bowls, the more likely it is that English speakers will instinctively start to say, "in the plate" instead of "on the plate," etc.

A: If a plate is has higher sides to it then it is a shallow bowl not a plate.
 As a Native English Speaker O have always said on the plate and in the bowl.
Agreed that  if a person said  they put  their fork in his plate  it would assume that it was into his food ..
If you said the fork was on the plate you would assume some sort of art work whereby the fork was embedded in the plate


text:
Q: Unable to locate framework.dir in sencha I have installed sencha cmd 4.0.4.84. But when i tried to create an App it is showing  Unalble to locate framework.dir property from sencha config.Ensure the command was executed from a valid framework direcotry.Non framework directory

A: It is exactly what it says: you are most likely running sencha from a wrong directory.
cd /where/you/extracted/ext-4.2.1
sencha generate app MyApp /where/you/want/myapp

For more details watch: Creating Workspace and Applications video.

A: I  made a big mistake- i was running from sencha command root. But it has to be running from
Extjs  version root.  we have to create a worklocation inside it. their will extjs folder and from their we need run the command to create the App. Now it is working perfectly

A: You'll want to take a look at the cmd tools and workspaces.
A little more specifically take a look at the framework locations section of the page.

A: It's better to go to the SDK folder just mention the SDK path in your command while generating the app:
sencha -sdk <YOUR SDK PATH> generate app <APP NAME> <PATH TO GENERATE APP>

A: Before creating any sencha app.
Understand 2 things.
1. Sencha CMD
2.Extjs framework.
Both are different.

Coming to point:.
1. Download the latest extjs framework.
2.Use the below command
sencha -sdk=path/to/ext generate app MyAPP path/to/worspace/of/MyApp

This will solve the above issue asked in question.
Danke,
Rahul


text:
Q: Setting up Apache Mahout to use MySql I am a .NET developer by trade, but I am working on a REST service implementation of Mahout for our website. I am having trouble setting up Mysql as the DataSource for MySQLJDBCDataModel. This is essentially how I am trying to go about it (Yes it is copy and pasted from Mahout In Action.)
MysqlDataSource dataSource = new MysqlDataSource ();
dataSource.setServerName("my_database_host");
dataSource.setUser("my_user");
dataSource.setPassword("my_password");
dataSource.setDatabaseName("my_database_name");
JDBCDataModel dataModel = new MySQLJDBCDataModel(
dataSource, "my_prefs_table", "my_user_column",
"my_item_column", "my_pref_value_column");

The problem is that Java is not recognizing "MysqlDataSource" as a valid object and won't compile. When I try to include "com.mysql.*" it says it can't resolve that either.
Any help would be great

A: Is your MySQL driver in the java classpath? See if this link here helps.
Next time, please post details of your setup, like which server hosts your app.


text:
Q: Python 3 JSON deserializer: JSON object must be str, not 'bytes' There are couple of questions related to this error:

JSON object must be str, not 'bytes'

However, except obvious solution to read and decode response, I didn't learn anything special.
Here is example to the problem:
>>> import json
>>> from urllib.request import urlopen
>>> url = 'http://echo.jsontest.com/key/value/one/two'
>>> with urlopen(url) as request:
...     json.load(request)
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "C:\Python35\lib\json\__init__.py", line 268, in load
    parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
  File "C:\Python35\lib\json\__init__.py", line 312, in loads
    s.__class__.__name__))
TypeError: the JSON object must be str, not 'bytes'

So my question is why Python's JSON deserializer (that accepts file-like objects with .read() method), does not try to handle this request, as response headers hint all there is needed to know:

Content-Type: application/json; charset=ISO-8859-1

Headers hint, they do not guarantee, but that can not be a reason not to try the obvious IMHO.

A: Use json.loads instead of json.load


text:
Q: Error while giving Powershell access to Target System from Source machine I am basically a C# guy but my requirement is to give Powershell access to the remote/target systems (Say Client) from my system (Say Server). I am part of the administrator group in those remote/target machines. Also, all the systems including mine are in the same domain. I tried running these commands in my system (Server)-

Enable-PSRemoting -Force
Invoke-Command -ComputerName client01,client02 -ScriptBlock { SET -executionPolicy ExecutionPolicy Unrestricted }

I get following error message-
Powershell Remoting Error

A: You need to run Enable-PSRemoting on your target systems first or apply some group policy that achieves the same end
If you need something only small scale or are just in testing phase, simply remote desktop to your clients and run Enable-PSRemoting -force from an elevated shell.
There are already pretty good articles out there that explain how to use group policy to enable remote powershell on a large number of clients.


text:
Q: how to alternate or change words on Wordpress templates? This is an example I'm trying to achieve.
Let say I have the USA states and each state has 5 cities and a custom template with content for each state.
I want to alternate/change the city names on each city page without changing the content.
If I visit California, then I click San Diego I want it to say blah blah blah Sandiego blah blah blah, then if I click on Los Angeles I want it to say blah blah blah Los Angeles blah blah blah.
I'm doing templates on the hierarchy that will have this content.
I'm trying to save time by creating one template and alternating the names of the cities around the text.
the content can stay the same, just the cities have to change one each state.
I created one template for each state, tho I need to use that same template for each city.

A: In WordPress to implement local pages for States and Cities we can use WordPress pages (we can go custom post route also but sometimes clients preferred root level pages for url without deep nesting i.e. site.abc/state instead of site.abc/cpt/state)

*

*We can add States as Pages, to have State Full name and short-name tracking, we used it like:
Page name: State Full Name e.g. New York
Slug : short-two letter code e.g. ny

So any given time once on the state page we have State Full name from title, state short-code from page slug etc..

*For Cities we can make them look like child pages for state using addressing and WP permalink rules e.g. site.abc/st/city

This url gives us two clues, i.e it is child page so it is City page, so we will be loading city template for this page, and parent part tells which page/state it belongs to so we can fetch some data from there too like to show all other cities in the end from same state etc.
For URL Parsing: (Untested code, just for ideas)
function custom_endpoints() {
add_rewrite_rule(
    '([^/]{2})/([^/]*)',
    'index.php?state=$matches[1]&city=$matches[2]',
    'top'
);

add_rewrite_tag( '%state%', '([^&]+)' );
add_rewrite_tag( '%city%', '([^&]+)' );
}
add_action( 'init', 'custom_endpoints' );

Now we can add those rewrite tags into query as query_vars
function em_query_vars($vars) {
    array_push($vars, 'state');
    array_push($vars, 'city');
    return $vars;
}
add_filter('query_vars','em_query_vars');

Now For template loading we can use those query tags: (Untested Code, only for ideas)
add_filter('template_include', 'custom_function_for_templates', 1, 1);
 function custom_function_for_templates($template) {

    global $wp_query;
    if (isset($wp_query->query_vars['state']) && isset($wp_query->query_vars['city'])) {
$slug = $wp_query->query_vars['city'];

return plugin_dir_path( __FILE__ ). '/templates/city-template.php';
    }
    if (isset($wp_query->query_vars['state'])) {

        return plugin_dir_path( __FILE__ ). '/templates/state-template.php';
    }

    return $template;
}

Lastly in the template, you can use current query tag for City to replace wherever in the content you have %%city%% and %%st%% and %%state%% tags to replace with correct city name to display the page with content relevant to current city and state.
Hope it will give you enough ideas to implement it as per your current setup. Code I have included is not tested so it may not work. But Hooks and Filter from WordPress Api used are correct ones so you can always hook your own logic/function to those steps to make it happen.
Edit: Search Replace Operations on Php Level in the Template
$content = str_replace("%%city%%", $new_page, $content);
$content = str_replace("%%state%%", get_the_title($state), $content);
$content = str_replace("%%st%%", strtoupper(get_post_field( 'post_name',$state)), $content);

Here you will see I am search/replacing the content's any tags used there


text:
Q: Plotting history of accuracy in BaggingClassifier I've trained a simple random forest algorithm and bagging classifier (n_estimators = 100). Is it possible to plot the history of accuracy in bagging Classifier? How to calculate the variance of in 100 samples?
I've just printed the accuracy value for both algorithms:
# DecisionTree
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.90)
clf2 = tree.DecisionTreeClassifier()
clf2.fit(X_tr, y_tr)
pred2 = clf2.predict(X_test)
acc2  = clf2.score(X_test, y_test)
acc2  # 0.6983930778739185

# Bagging
clf3 = BaggingClassifier(tree.DecisionTreeClassifier(),  max_samples=0.5, max_features=0.5, n_estimators=100,\
                         verbose=2)
clf3.fit(X_tr, y_tr)
pred3 = clf3.predict(X_test)
acc3=clf3.score(X_test,y_test)
acc3 # 0.911619283065513

A: I don't think that you can get this information from the fitted BaggingClassifier. But you can create such a plot by fitting for different n_estimators:
import matplotlib.pyplot as plt

from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import BaggingClassifier

from sklearn import datasets
from sklearn.model_selection import train_test_split

iris = datasets.load_iris()
X, X_test, y, y_test = train_test_split(iris.data,
                                        iris.target,
                                        test_size=0.20)

estimators = list(range(1, 20))
accuracy = []

for n_estimators in estimators:
    clf = BaggingClassifier(DecisionTreeClassifier(max_depth=1),
                            max_samples=0.2,
                            n_estimators=n_estimators)
    clf.fit(X, y)
    acc = clf.score(X_test, y_test)
    accuracy.append(acc)

plt.plot(estimators, accuracy)
plt.xlabel("Number of estimators")
plt.ylabel("Accuracy")
plt.show()

(Of course, the iris dataset is easily fit with just a single DecisionTreeClassifier, so I set max_depth=1 in this example.)
For a statistically meaningful result, you should fit a BaggingClassifier multiple times for each n_estimators and take the average of the obtained accuracies.


text:
Q: Moving IBM MQ away from mainframe - best practice? Today we have our MQ installations primarely on mainframe, but are considering moving them to Windows or Linux instead.
We have three queue managers (qmgrs) in most environments. Two in a queue sharing group across two LPARs, and a stand-alone qmgr for applications that doesn't need to run 24/7. We have many smaller applications, which shares the few qmgrs.
When I read up on building qmgrs in Windows and Linux, I get the impression that most designs favor a qmgr or a cluster per application. Is it a no-go to build a general purpose qmgr for a hundred small applications on Windows/Linux?
I have considered a Multi instance Qmgr (active/passive) or a clustered solution.
What is considered best practice in a scenario, where I have several hundred different applications that needs MQ communication.

A: First off, you are asking for an opinion that is not allowed on StackOverflow.
Secondly, if you have z/OS (mainframe) applications using MQ then you cannot move MQ off the mainframe because there is no client-mode connectivity for mainframe applications.  What I mean is that the mainframe MQ applications cannot connect in client mode to a queue manager running on a distributed platform (i.e. Linux, Windows, etc.).  You will need to have queue managers on both mainframe and distributed platforms to allow messages to flow between the platforms.  So, your title of "Moving IBM MQ away from mainframe" is a no go unless ALL mainframe MQ applications are moving off the mainframe too.

I get the impression that most designs favor a qmgr or a cluster per
application.

I don't know where you read that but it sounds like information from the 90's.  Normally, you should only isolate a queue manager if you have a very good reason.

I have considered a Multi instance Qmgr (active/passive) or a
clustered solution.

I think you need to read up on MQ MI and MQ clustering because they are not mutually exclusive.  MQ clustering has nothing to do with fail-over or HA (high-availability).
Here is a description of MQ clustering from the MQ Knowledge Center.

A: You need to understand and  document your requirements.
What failover time can you tolerate?
With Shared queue on z/OS if you kill one  MQ - another MQ can continue processing the messages within seconds.  Applications will have to detect the connection is broken and reconnect.
If you go for a mid range solution, it may take longer to detect a queue manager has gone down, and for the work to switch to an alternative.  During this time the in-transit messages will not be available.
If you have 10 mid range queue managers and kill one of them, applications wich were connected to the dead queue manager can detect the outage and reconnect to a different queue manager within seconds, so new messages will have a short blip in throughput.  Applications connected to the other 9 queue managers will not be affected, so a smaller "blip" overall.
Do you have response time criteria?   So enterprises have a "budget" no more than 5 ms in MQ, no more than 15 ms in DB2 etc.
Will having midrange affect response time, for example is there more or less network latency between clients and servers.
Are you worried about confidentiality of data.  On z/OS you can have disk encryption enabled by default.
Are you worried about security of data, for example use of keystores, and having stash files (with the passwords of the keystore) sitting next to the keystore.  Z/OS is better than mid range in this area.
You can have tamper proof keystores on z/OS and midrange.
Scaling
How many distributed queue managers will you need to handle the current workload, and any growth (and any unexpected peaks).  Does this change your operational model?
If you are using AMS, the maintenance of keystores is challenging.  If you add one more recipient, you need to update the keystore for all userids that use the queue- on all queue managers.  With z/OS You update one key ring per queue manager.
How would the move to midrange affect your disaster recovery?  It may be easier (just spin up a new queue manager) with midrange, or harder - you need to create the environment before you can spin up a new queue manager.
What is the worst case environment, for example the systems you talk to - if they went down for a day. Can your queue managers hold/buffer the workload?
If you had a day's worth of data, how long would it take to drain it and send it?
Where are your applications? - if you have applications running on z/OS (for example , batch, CICS, IMS,  WAS) they all need a z/OS queue manager on the same LPAR.  If all the applications are not on z/OS then they can all use client mode to access MQ.
How does security change? (Command access, access to queues)


text:
Q: Htmlunit get form input by ID instead of name I have a form that has multiple rows and similar inputs. They have different IDs but the same name.
<input id="E2EMPL1" class="uppercase required" type="text" value="" maxlength="9" size="9" name="E2EMPL">

<input id="E2EMPL2" class="uppercase required" type="text" value="" maxlength="9" size="9" name="E2EMPL">

I can fill in the first row, no problem, but when it comes to filling in the 2nd row, I can't figure it out.
This is to fill out the first row:
            HtmlPage mainPage = webClient.getPage(siteName);
            form = mainPage.getFormByName("timeForm");

            for (TimeEntry te: aList){
               form.getInputByName("chkaction").setValueAttribute("checked");
               form.getInputByName("E2EMPL").setValueAttribute(te.getResource());
               form.getInputByName("ww_fE2WKDT").setValueAttribute(te.getEntryDate());
            }

But I'm not sure how to fill out the 2nd row when the name stays the same, but the ID changes to EMPL1, EMPL2, etc. I think I'm suppose to use xpath but I'm not sure how?
form.getByXPath("//input[@id='E2EMPL2']"); ???
Edit: As a side note. I have tried with HTTPClient to just POST the data. Unfortunately, it doesn't work for this form, and I have no idea why. I've asked a question on here that never got any answers and don't have enough rep to put a good bounty on it. However, I just gave HTMLUnit a try and if I fill in the form, and hit the submit button, it will work just fine. This is why I don't use HTTPClient.
If anybody wants to see the question, I deleted it, but I'll undelete it if anybody really wants to see it.
The HTML form has 5 rows of data, and it's a little slow to fill one row, click submit 5 times vs fill the 5 rows and then click submit. I was hoping it'd be a little faster, but if it's impossible to do this, I'll give up on this. I was hoping some people could have an insight.

A: Try this:
HtmlForm Form = htmlPage.getHtmlElementById("form id");

A: You can get the element as a DomElement (instead of an InputElement) and set its value attribute:
HtmlPage mainPage = webClient.getPage(siteName);

DomElement e2empl1 = mainPage.getElementById("E2EMPL1");
if (e2empl1.getTagName().toLowerCase().equals("input")) {
    e2empl1.setAttribute("value", "value1");
}

DomElement e2empl2 = mainPage.getElementById("E2EMPL2");
if (e2empl2.getTagName().toLowerCase().equals("input")) {
    e2empl2.setAttribute("value", "value2");
}

(Maybe you can skip the tagname check)


text:
Q: Site optimization - PHP and memory usage + database? I am building a news site, written in php. Pages on the website, have content that needs to be automatically updated, depending on some information on the website. My idea was to create one .txt file, that will contain all those information, so I can access it via php and modify pages on the site. When user loads the site, PHP script runs and reads whole file into a string, splits it two times and then works with this strings. But, possible problem is that this .txt file can be really big (like 10mb) and with a lot of traffic, it is probably bad idea to read file this big every time user loads a page, so I probably need something faster and better. Possible solution is mysql database, but would it make big difference? Also, are there some tricks to optimize website performance using PHP?
NOTE: Here is script that reads the file:
 <?php
$myfile = fopen("postovi.txt", "r") or die("Unable to open file!");
$smejanje = fread($myfile,filesize("postovi.txt"));
$postovi= explode("<novipost>", $smejanje);

$i = 0;
        $duzina = sizeof($postovi);
        while ($i < $duzina) //duzina = broj postova <ucitava sve postove>
        {
            $postovi[$i] = explode("|", $postovi[$i]);
            $i++;
        }

fclose($myfile);

and here is html element that is to be updated with information from that file:
<?php $id++; ?>

        <a href="<?php echo($postovi[$id][0]); ?>" id="<?php echo("mali-post-link-".$id); ?>">
        <div class="mali-post" style="background-image: url(<?php echo $postovi[$id][3]; ?>);" id="<?php echo("mali-post-".$id); ?>">

        <p id="<?php echo("mali-post-naslov-".$id); ?>" class="customfont"><?php echo $postovi[$id][2]; ?>

  <?php echo $znak ?>   <?php
        $time = strtotime($postovi[$id][4]);
        echo ' pre '.humanTiming($time); ?>

A: If you have 10MB of data that needs to be available to every page, I suggest having that data in RAM rather than loading it from any disk-based data source.  While MySQL will probably cache the data in RAM, retrieving and formatting data from MySQL is slower than just keeping the processed data in PHP.
For information on how to share memory, see Reading and writing global variables across scripts in PHP

A: I feel that the case for using databases to store and retrieve data has already been made. A text file will only get you so far - probably only useful for very very small tasks. I would recommend reading a book or finding a good tutorial online to learn how to use MySQL correctly in your PHP applications. MySQL is free, although depending on your needs you may need to have it hosted somewhere online.
Once you learn the basics, there are all kinds of strategies you can employ to speed up your queries. For example, you can pull down much more than you need with a single query and then use PHP to sort out the results. Calls to a database server tend to take more time than CPU cycles.


text:
Q: Using DOMDocument to wrap all nodes between header tags in div I have a set of HTML files to process where related sections are not grouped in containers and can contain virtually any element.  New sections are currently only delineated by the next header tag:

Section 1

Paragraph Text

Paragraph Text

Section 2

Paragraph Text

Further Paragraph Text

Section 3

Paragraph Text

Paragraph Text

How can I use the DOM functions in PHP to wrap all content between these header tags in a
?  I.e. transforming the above HTML into:

Section 1

Paragraph Text

Paragraph Text

Section 2

Paragraph Text

Further Paragraph Text

Section 3

Paragraph Text

Paragraph Text

So far I have tried various combinations of loops and XPATH selectors to try and gather all the elements between headers so that I can wrap them as above - but haven't been successful in doing this.

A: My initial thoughts were based around manipulating the output buffer as I had failed to read the opening paragraph properly and the following function was used as a callback to ob_start.
You might notice the use of $tags towards the start of the function and followed by the rather complicted $query - the $tags is used later to aid populating found nodes and to ensure we stop when the next node found is in that $tags array - rather than write the pattern and maintain this array independently I figured it would be more flexible like this.
Essentially it works like this: Construct a query pattern from the supplied $tags array and use that to query the HTML DOM. If there are matching nodes, iterate through the collection and add the found node( a header ) to an array. Then iterate over the siblings of the found node and add these to the same new array. Before the loop moves to the next node in the collection save this array before repeating the process. Once all the discovered nodes have been processed it is time to create the container DIV elements ensuring that all children are once again populated.
<?php
    #https://stackoverflow.com/questions/59234379/using-domdocument-to-wrap-all-nodes-between-header-tags-in-div/59235431#59235431

    function wrapcallback( $buffer ){
        global $use_output_buffer;

        $delimiter='#';
        $tags=array('h1','h2','h3','h4','h5','h6');
        $query=implode('|', explode( $delimiter, sprintf( '//%s', implode( sprintf( '%s//', $delimiter ), $tags ) ) ) );
        $keepers=array();
        $parents=array();

        libxml_use_internal_errors( true );
        $dom=new DOMDocument;
        $dom->validateOnParse=false;
        $dom->recover=true;
        $dom->strictErrorChecking=false;
        $dom->preserveWhiteSpace=true;
        $dom->loadHTML( $buffer );
        $errors = libxml_get_errors();
        libxml_clear_errors();

        $xp=new DOMXPath( $dom );
        $col=$xp->query( $query );

        if( $col->length > 0 ){
            foreach( $col as $node ){

                $parents[]=$node->parentNode;
                $nodes=array( $node );

                while( $node = $node->nextSibling ){
                    if( in_array( $node->nodeName, $tags ) )break;
                    if( $node->nodeType==XML_ELEMENT_NODE  )$nodes[]=$node;
                }
                $keepers[]=$nodes;
            }
        }

        foreach( $keepers as $index => $obj ){
            $div=$dom->createElement('div');
            $parents[ $index ]->appendChild( $div );
            foreach( $obj as $child )$div->appendChild( $child );
        }

        $keepers = $parents = $xp = $div = null;
        echo $dom->saveHTML();
    };

    $html="
    <!DOCTYPE html>

            <title>It's a Christmas Wrapper!</title>

Section 1

Paragraph Text

Paragraph Text

Section 2

Paragraph Text

Further Paragraph Text

Section 3

Paragraph Text

Paragraph Text

    ";

    wrapcallback( $html );

?>


text:
Q: Permission Denied CreateObject("Excel.Application.16") I'm working on a legacy web application written in classic asp on a Windows Server 2022. Excel 2016 is installed. This has been working fine on an older machine. This is a new instance of the site (on AWS).
Trying to open an uploaded Excel file and get the 'Permission Denied' and references the line;
Set objExcel = CreateObject("Excel.Application.16")

I have granted IIS_IUSRS read, write and execute permission to the file directory and to the Office 16 folder.
Still getting errors.

A: Go to Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Classes\ of your system by using Registry Editor app.
There you can find out the name of the class installed.
Something like
Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Excel.Application
or
Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Excel.Application.16
or some other class name.
Use that name to create the object.
Set objExcel = CreateObject("<<NAME THAT YOU SEE IN REGISTRY FOR EXCEL>>")


text:
Q: Forgot my only administrator account password? I am on a XP Professional PC, I only have a administrator account for which I forgot the password. How can I fix this login issue?
I cannot format because I have important data on the system. Steps I tried after googling is from safe mode, logging in with a blank password with administrator account. Let me remind I only have a administrator account, no guest account nor a child account.

A: There is a Linux program called chntpw that you can use to reset the password. You can download a boot disk from here. Burn the boot CD image (or use the USB boot image if you have a flash drive), and follow the instructions to select the partition, registry directory, and password reset options.
Once you are finished with the whole process, reboot. You should be able to log in with a blank password.


text:
Q: Bash scripting on debian installer not accepting user input on preseeding I have a very small script that needs to be run on debian installer: (via preseeding, pre installation script)
echo -n -e " # Your option [1] [2] [3]: "
    read REPLY
    if [ "$REPLY" == "1" ]

The script stops here and whatever I press is just displayed onto screen however it is not accepting the enter key. Normally, when you press 1 and press enter, the read should return 1 to $REPLY. But nothing happens. It keeps accepting user input but no further action happens.
Then, I switched to tty2 with ALT+F2 and run the script there, it was fine, it works as expected, when I press; it takes the input. Why tty1 is not accepting enter as usual?

A: Use debconf for that kind of configuration, it tackles exactly needs like yours.
Adapted example from the manual
Template file (debian/templates):
Template: your_package/select_option
Type: select
Choices: 1, 2, 3
Description: Which option?
 Choose one of the options

Script (debian/config):
#!/bin/sh -e

# Source debconf library.
. /usr/share/debconf/confmodule

db_input medium your_package/select_option || true
db_go

# Check their answer.
db_get your_package/select_option
if [ "$RET" = "1" ]; then
   # Do stuff
fi

A: Had the same problem (read not processing my input) with busybox on an embedded Linux.
Took me some time to realize that busybox's read is not CR-tolerant — my terminal program (used miniterm.py) sent CR/LF line ends by default;  switching it to LF only solved my problem!

A: with bash interpreter, try replace read by :
builtin read
with other sh interpreter, specify the variable name :
read REPLY

A: The following script works fine for me:
#!/bin/sh
echo -n -e " # Your option [1] [2] [3]: "
read

case $REPLY in
    1 )
      echo "one" ;;
    2 )
      echo "two" ;;
    3 )
        echo "three" ;;
    *)
        echo "invalid" ;;
esac

It prints out one nicely if I choose 1. Any reason why you'd like to stick to if...fi?


text:
Q: How to make three column template in codeigniter?
      I am a newbie to CI.And I want to implement a CI in a three column template manner.But I am not sure how can I implement it.The right column is static one once the user logged into the site.It contains like profile pic,Accountinfo and some other stuffs.
In the middle and left columns are going to be  change depend upon the user operation link on the right side.
--------------------------------------------
                 Header

Left     |    Middle       |         Right
  Pic    |                 |
  Account|                 |

                Footer
----------------------------------------------

For example if user clicks the  left side link account I need to display account information in the middle panel.So Now the middle panel only changes in content?How can I achieve this?

A: just display views depending on the method requested..
<?php
class Profile extends Controller {

    function __construct()
    {
        parent::__construct();
    }

    function index()
    {
        $this->load->view('profile/home');
    }

    function messages()
    {
        $this->load->view('profile/messages');
    }

    function pictures()
    {
        $this->load->view('profile/pictures');
    }
}

and so on.
however it sounds like you want to keep parts of the site the same, so it may be worth looking in to a template library which will allow you to have one layout, but be able to write to specific regions - making the app easier to maintain etc.
see:
http://codeigniter.com/forums/viewthread/95687/P40/
http://philsturgeon.co.uk/code/codeigniter-template
to summarise - code as required within your controller/model to present the correct view to the user, based on the requested method.


text:
Q: CSV to XML trnformation using cloveretl I want to transform my csv file to XML using cloveretl.
I gone through the basic tutorial, all explains abound direct mapping from csv to xml, csv header column names are used for xml element name.
I have one complex XSD, and I want to map csv to that XSD generated xml.
When I generate metadata using my XSD 213 fmt file generated in cloveretl.
How do map all these together ?
I saw an option to map individually, one csv metadata to one fmt. Like this I have to do 213 mapping and combine all ?

A: I assume you have two components: UniversalDataReader and XMLWriter. The edge between them should not have the metadata from the XSD schema (you do not have to extract metadata from the XSD at all), it should have metadata extracted from the input CSV file. Otherwise, you would not be able to read the file in the first place.
Then, in XMLWriter, you can set the XSD schema or create the mapping manually. For more information, see http://doc.cloveretl.com/documentation/UserGuide/topic/com.cloveretl.gui.docs/docs/extxmlwriter.html#xsd-mapping
If the CSV and the result XML are simple enough, you do not need the XSD schema at all.


text:
Q: search specific string in a value from Json and assign to variable in ruby Here is my json file
{
  "osNameSpace" : "prod",
  "bucketNames" : [ "RC_osbackup_config_d0007cz_idfdafa3", "IC_osbackup_vman_d0007cz_dasdc3w" ],
  "user" : "RC_osbackup_svc_user_d0007cz_dasf2fd",
  "userOcid" : "rcid1.user.oc1..aaaaaaaazf5e27hbpst2pxarisi5qvkmgotwm5ro4nhjkkjq4mmxengckv2a",
  "group" : "RC_osbackup_svc_grp_d0007cz_asdf24"
}

I want to search for a string 'osbackup_config' and assign to 'os_conf' variable. similarly for string 'osbackup_vman' to 'os_vman'
I tried the following, but no luck
input_file="/root/testjson_2.json"
r = JSON.parse(File.read(input_file))

r["bucketNames"].find {|r1| r1['dbbackup_rman']=='rman'}['rman_bucket_name']
r["bucketNames"].find {|r1| r1['dbbackup_config']=='config'}['config_bucket_name']

A: Why not this?
r['bucketNames'].find { |v| v.include?'osbackup_config' }

or
os_conf  = r['bucketNames'].find { |v| v['osbackup_config'] }

osbackup_vman = r['bucketNames'].find { |v| v['osbackup_vman'] }


text:
Q: How can I open new tab in bootgrid link column? I have used a bootgrid based database with links and is working fine. But my problem is that whenever I click the link it opens in the same window. How can I force the browser to open the link in a new tab?
I tried using the target="_blank" but it's not working. Here is the formatter:
formatters: {
            "link": function(column, row) {
                        return " Download "
            }
}

A: Try this, it works for me:
formatters: {
  "link": function(column, row) {
    return " Download ";
   }
}


text:
Q: Elasticsearch-php 5.x - Can't put templates Using the official elasticsearch-php client, version 5.x.
I'm trying to put a template inside my Elasticsearch instance, but it simply
doesn't return anything.
$data = [
        'name' => 'testTemplate',
        'body' => [
            'template' => 'testTemplate-*',
            'mappings' => [
                'foo' => 'string',
                'bar' => 'string',
            ],
        ],
    ];
$this->client = ClientBuilder::create()
    ->allowBadJSONSerialization()
    ->setHosts($host)
    ->build();
$this->client->putTemplate($data);

I must use allowBadJsonSerialization() because i'm running on PHP 5.4, but on 5.6 it does the same thing.
I don't know if it's a bug or i'm doing something wrong.
Can you help me? Thanks.

A: I solved this by using CURL according to documentation.
Unfortunately the library doesn't work for the 5.x branch.


text:
Q: R - =if max statement from excel to R Within a data frame. I want to compare today's value against a look back 'n' day period.
I know how to do it in excel for comparing today's value to see if it was higher than the previous 10 days.
=IF(A11>MAX(A1:A10),1,0)

How can I do the same logic within a function in R?
The output would look like this below:
  Column Output
1   12    NA
2   13    NA
3   14    NA
4   15    NA
5   9     NA
6   9     NA
7   7     NA
8   8     NA
9   16    NA
10  17    NA
11  20    1
12  14    0
13  9     0
14  8     0
15  6     0
16  5     0
17  28    1

In row 11. Because value 20 is higher than the previous 10 days it denotes a 1 value.
In row 12, because value 14 is not the highest number in previous 10 days it receives a 0 value.
And it of course rolls on moving 10 day window.

A: P Lapointe's answer is great but anytime I'm doing a 'rolling' calculation my first instinct is to think of rollapply from the zoo package.
is_last_greatest <- function(x){
    #' Given an input vector this returns
    #' 1 if the last element is greater than
    #' all of the other elements and 0 otherwise
    ifelse(all(tail(x,1) > head(x,-1)), 1, 0)
}

# We want to compare to the previous 10 values but the function
# I wrote requires us to include the value we're using as
# comparison so I set the width to 11
output <- rollapply(dat,
          width = 11,
          FUN = is_last_greatest,
          fill = NA,
          align = "right")

cbind(dat, output)

which gives
      dat vals
 [1,]  12   NA
 [2,]  13   NA
 [3,]  14   NA
 [4,]  15   NA
 [5,]   9   NA
 [6,]   9   NA
 [7,]   7   NA
 [8,]   8   NA
 [9,]  16   NA
[10,]  17   NA
[11,]  20    1
[12,]  14    0
[13,]   9    0
[14,]   8    0
[15,]   6    0
[16,]   5    0
[17,]  28    1

A: Here's how to do that with roll_maxr from RcppRoll.
library(RcppRoll)
df$Output2 <- ifelse(df$Column>roll_maxr(lag(df$Column),11, na.rm = TRUE),1,0)

   Column Output Output2
1      12     NA      NA
2      13     NA      NA
3      14     NA      NA
4      15     NA      NA
5       9     NA      NA
6       9     NA      NA
7       7     NA      NA
8       8     NA      NA
9      16     NA      NA
10     17     NA      NA
11     20      1       1
12     14      0       0
13      9      0       0
14      8      0       0
15      6      0       0
16      5      0       0
17     28      1       1

data
df <- read.table(text="  Column Output
1   12    NA
                 2   13    NA
                 3   14    NA
                 4   15    NA
                 5   9     NA
                 6   9     NA
                 7   7     NA
                 8   8     NA
                 9   16    NA
                 10  17    NA
                 11  20    1
                 12  14    0
                 13  9     0
                 14  8     0
                 15  6     0
                 16  5     0
                 17  28    1",header=TRUE,stringsAsFactors=FALSE)

A: Here is a base R method using embed to construct the comparison sets and performing the comparisons with apply.
# get a matrix for comparisons
myMat <- embed(df$Column, 11)

Here, this returns
myMat
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11]
[1,]   20   17   16    8    7    9    9   15   14    13    12
[2,]   14   20   17   16    8    7    9    9   15    14    13
[3,]    9   14   20   17   16    8    7    9    9    15    14
[4,]    8    9   14   20   17   16    8    7    9     9    15
[5,]    6    8    9   14   20   17   16    8    7     9     9
[6,]    5    6    8    9   14   20   17   16    8     7     9
[7,]   28    5    6    8    9   14   20   17   16     8     7

So the goal is to compare the value in the first column with those in the remaining column for each row.
as.integer(max.col(myMat) == 1L)
[1] 1 0 0 0 0 0 1

Now, tack on the appropriate number of NA values, which is the number of columns in myMat minus one.
df$output2 <- c(rep(NA, ncol(myMat) - 1), as.integer(max.col(myMat) == 1L))

this returns
df
   Column Output output2
1      12     NA      NA
2      13     NA      NA
3      14     NA      NA
4      15     NA      NA
5       9     NA      NA
6       9     NA      NA
7       7     NA      NA
8       8     NA      NA
9      16     NA      NA
10     17     NA      NA
11     20      1       1
12     14      0       0
13      9      0       0
14      8      0       0
15      6      0       0
16      5      0       0
17     28      1       1

An advantage of max.col is that it is quite fast. One of its biggest drawbacks is that it does not have an na.rm argument to remove missing values. In the case that there are missing values, here is a method using apply on myMat instead of max.col.
apply(myMat, 1, function(x) as.integer(all(head(x, 1) > tail(x, -1))))

The operating comparison function here is
all(head(x, 1) > tail(x, -1))

Functions that produce the same result include the following
head(x, 1) == max(x) # or
x[1] == max(x)

and
1L == which.max(x)


text:
Q: Is there an equivalent of Java's AssertionError in Ruby? I'm trying to write some test helpers for a gem, and would like to provide some assertions that will trigger test failures where appropriate.
In Java, this is achievable (if I recall) by throwing an AssertionError, which should then get picked up by the test runner and Just Work. Does anything like this exist for Ruby?
For example, let's say I have a gem emily-post, which provides some helpful methods for checking how polite a request is:
request = 'I can haz cheezburger?'
EmilyPost.is_polite?(request) # false

request = 'I can haz cheezburger, please?'
EmilyPost.is_polite?(request) # true

Let's say as part of this gem I want to provide test helpers that can:

*

*Set up an (im)polite request

*Verify that the response is also polite

For example my test might read like:
include EmilyPost::TestHelpers

with_polite_request do
    response = 'No way!'
    issue(response) # This rude response should fail the test
end

The code for with_polite_request might look something like:
def with_polite_request
    request = 'I can haz cheezburger, please?'
    yield
    raise AssertionError unless is_polite?(response)
end

...where AssertionError would preferably be some error recognised by any test framework as a failure, rather than an error.
Does any such error exist?


text:
Q: Dwarf Fortress World Gen I'm trying to generate a very specific map: one with an arctic ocean, a volcano, and preferably a taiga (or other frozen, wood-filled land).
I've managed to generate a couple of coastal volcanoes so far, (including one with a sub-ocean magma pipe. that was a fun embark -- 5 minutes of "cave in has occurred" as water became obsidian and then fell to the bottom of the magma sea) but they're never close enough to the poles to be in an arctic ocean. (I have a strong desire to acquire War Walruses, you see, so I simply must have an arctic biome :P )
Is there any way I can decrease the temperature on an already generated world? How can I increase the number of Cold or Freezing squares on each map?

A: So from what I gather is that you want to create a specific map or decrease the temperature on an already created map.  I don't know the latter but I can help with the former:

*

*Open up DF

*On the main screen select Design New World With Parameters

*Select one of the presets and press the e key

*Scroll down till you see the following (should be the second page):

*Change the Maximum Temperature and Minimum Volcanism values

*

*good values for Temperature are ~45

*good values for Volcanism are >50

*Finally, to ensure a good Taiga you'll want to play with the Rainfall parameter.