text:
Q: reading from disk multiple times possibly cause bottleneck I'm trying to find out where the bottleneck of a ruby script is. I suspect that it might happen because the script parses thousands of lines and, for each one, it checks if a certain file is present in disk and eventually reads its contents.
def sectionsearch(brand, season, video)
  mytab.trs.each_with_index do |row, i|

    # ...some code goes here...
    f = "modeldesc/" + brand.downcase + "/" + modelcode + ".html"
    if File.exist?(f)
      modeldesc = File.read(f)
    else
      modeldesc = ""
    end
    # ...more code here...

  end
end

Given that there are no more than 30 different "modelcode" files for thousands of record, I was looking for a different approach that reads all the content of the folder before the each loop (since it is not going to change during the execution).
Is this approach going to speed up my script, also is this the right way to implement this?

A: I would probably do something like a hash (passing a block) to check for the file, on unknown keys:
def sectionsearch(brand, season, video)

   modeldescrs = Hash.new do |cache, model|
      if File.exist?(model)
        cache[model] = File.read(model)
      else
        cache[model] = ''
      end
    end

  mytab.trs.each_with_index do |row, i|

    # ...some code goes here...
    f = "modeldesc/" + brand.downcase + "/" + modelcode + ".html"
     puts modeldescrs[f]
    # ...more code here...

  end
end

then just access modeldescrs[f] when you need it (the puts above is an example)  if the key doesn't exist the block will be executed and it will look it up / populate it.   see http://www.ruby-doc.org/core-2.0/Hash.html  for more info on the block form of the initializer for Hash
Also you could make modeldescrs an instance variable if it needs to be saved.


text:
Q: Fibonacci Like Sequence I'm working on this problem but I'm not sure how to solve it.
Consider a sequence of positive integers $1, a_2, a_3, \dots , a_k=55$ where each term in the sequence is the sum of any two previous (not necessarily distinct) terms. What is the smallest value of $k$ such that the sequence exists?
Just for clarification, a possible sequence would be $1, 2, 4, 8, 16, 32, 48, 52, 54, a_{10}=55$, where the second through sixth terms are created by adding the previous term twice, the seventh term is created by adding 16 to the previous term, the eighth term is created by adding 4 to the previous term, the ninth term is created by adding 2 to the eighth term, and 55 is created by adding 1 to the ninth term. This sequence would have $k=10$.
I found a possible sequence for $k=9$, which is $1, 2, 4, 6, 12, 24, 48, 54, 55$, and I'm pretty sure I can't find one for $k=8$. However, I'm not sure how to prove that $k=9$ is the lowest I can go. Thanks for any help on this problem.

A: A proof, though not satisfying, is to perform breath-first search over all sequences. I verified that $k = 9$ is indeed the shortest possible sequence, for which there are $215$ sequences ending at $55$. Here are the sequences, and here is my code.
Maybe someone can find a clever proof :)

A: Partial and unhelpful answer:   $55 = 110111$ in binary.  So we can get an upper bound on $k$ by doubling till we get to $2^5$.  Then add numbers two at a time till we have all the ones we need in the binary expansion of $55$.
In binary:
$$a_1 =1, a_2=10, a_3=100, a_4=1000, a_5=10000, a_6=100000$$
(we'll have to re-order when we're done) then:
$$a_7=11, a_8=111, a_9 = 110000, a_{10}=110111.$$
So we need a term of the sequence for each power of two up to $2^5$ that is $5= \lfloor \log_2 55 \rfloor$ terms.  Then we need some more terms depending on how many binary digits there are.  If there are $m$ digits, it will take (I think) $m-1$ more terms.
(Or maybe $2^{\lceil log_2 m$ \rceil} $ more terms.)
I just toss this out there because 1. I'm really busy grading papers just now but 2. Maybe the binary idea will be helpful.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to configure web.config for multiple virtual applications in Azure App Service? I am trying to have multiple Node.js applications working in parallel in the same Azure App Service instance. I tried making a virtual application per Node.js app but I constantly get a server error (code 500). I use ZipDeploy or Azure DevOps to deploy my applications.
I suspect the problem might be that the web.config files associated with my applications is incorrect.
Here are some details on my setup:
In the Application settings menu of my App Service instance, I went to the Virtual applications and directories settings and put the following:
/                         site\wwwroot                        Application x
/mysite1                  site\wwwroot\mysite1                Application x
/mysite2                  site\wwwroot\mysite2                Application x

My wwwroot directory looks as follows. To make sure the problem doesn't come from the code itself, I used the same Node.js application for all three:
index.html
server.js
scripts
web.config (*)
----- mysite1
      |----- index.html
      |----- server.js
      |----- scripts
      |----- web.config (**)
----- mysite2
      |----- index.html
      |----- server.js
      |----- scripts
      |----- web.config (***)

I use the default web.config file (provided by Kudu) for the three of them:
<?xml version="1.0" encoding="utf-8"?>

<configuration>
  <system.webServer>

    <webSocket enabled="false" />
    <handlers>
      <add name="iisnode" path="server.js" verb="*" modules="iisnode"/>
    </handlers>
    <rewrite>
      <rules>
        <rule name="NodeInspector" patternSyntax="ECMAScript" stopProcessing="true">
          <match url="^server.js\/debug[\/]?" />
        </rule>

        <rule name="StaticContent">
          <action type="Rewrite" url="public{REQUEST_URI}"/>
        </rule>

        <rule name="DynamicContent">
          <conditions>
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="True"/>
          </conditions>
          <action type="Rewrite" url="server.js"/>
        </rule>
      </rules>
    </rewrite>

    <security>
      <requestFiltering>
        <hiddenSegments>
          <remove segment="bin"/>
        </hiddenSegments>
      </requestFiltering>
    </security>

    <httpErrors existingResponse="PassThrough" />

  </system.webServer>
</configuration>

Using this configuration, I can reach https://myappservice.azurewebsites.net/ without issue but https://myappservice.azurewebsites.net/mysite1 only returns a server error.
I tried taking off the handlers from the web.config files in subdirectories (** and ***) as instructed in similar questions but to no avail.
What is the correct configuration for these three files? I suppose the rewrite rules need to be adjusted but I am unsure what is the exact expected value for each.

A: I finally managed to pinpoint the exact problem through the IIS logs (/LogFiles/W3SVC.../ on Kudu) :
ModuleName="RewriteModule", Notification="SEND_RESPONSE", HttpStatus="500", HttpReason="URL Rewrite Module Error.", HttpSubStatus="52", ErrorCode="Cannot create a file when that file already exists.
 (0x800700b7)", ConfigExceptionInfo="\\?\D:\home\site\wwwroot\mysite1\web.config ( 16) :Cannot add duplicate collection entry of type 'rule' with unique key attribute 'name' set to 'NodeInspector'
"

What needed to be changed were the handler and rule names in the child web.config file, so that they wouldn't clash with the names in the parent web.config file. Everything works correctly now.

A: You could change Virtual applications and directories settings as below:
/                         site\wwwroot                Application x
/mysite1                  site\mysite1                Application x
/mysite2                  site\mysite2                Application x

When you deploy with zipdeploy or DevOps, the site name and Destination URL is like below:

For more details you could refer to Deploying multiple virtual directories to a single Azure Website.


text:
Q: What did Dumbledore put on the blank piece of paper for Mrs Cole? I've been re-reading this passage from the Half Blood Prince, and I'm just not too sure what Dumbledore did to get Mrs Cole to let her guard down around him, and am quite confused as to what Dumbledore did in general.

Apparently Dumbledore thought so too, for Harry now saw him slip his
  wand out of the pocket of his velvet suit, at the same time picking up
  a piece of perfectly blank paper from Mrs. Cole's desktop. "Here,"
  said Dumbledore, waving his wand once as he passed her the piece of
  paper, "I think this will make everything clear." Mrs. Cole's eyes
  slid out of focus and back again as she gazed intently at the blank
  paper for a moment.

But what was on the paper, if anything? Alternatively, did Mrs Cole just accept magic happened in front of her but not make a big deal out of it? Or did he discreetly cast a spell on her as her eyes slid in and out of focus?

A: The paper was entirely blank. From the very quote that you gave:

Apparently Dumbledore thought so too, for Harry now saw him slip his
wand out of the pocket of his velvet suit, at the same time picking up
a piece of perfectly blank paper [emphasis mine] from Mrs. Cole's desktop.

and

Mrs. Cole's eyes slid out of focus and back again as she gazed
intently at the blank paper [emphasis mine] for a moment.

He almost certainly used the Confundus Charm on her, since the Imperius Curse is Unforgivable, and this seems consistent with the effects of Confundo seen elsewhere, which make the target highly suggestible:

"But you've just done that!" said Hermione in Bellatrix's commanding,
arrogant voice. Travers looked around, eyebrows raised. The guard was
confused. He stared down at the thin golden Probe and then at his
companion, who said in a slightly dazed voice,
"Yeah, you've just checked them, Marius."
Harry Potter and the Deathly Hallows

A: My personal interpretation is there never was anything on the paper.  It was merely a prop he used to take her attention off him, and also to give the appearance everything was normal for any possible observers, so that he could cast a spell on her unnoticed to make her compliant, such as confundus.  Her eyes sliding in and out of focus were the only visible effects of whatever spell he had cast.


text:
Q: Show and hide different divs on clicks on different buttons I am trying to show and hide different div's on click on different buttons. For example, when I click button "1", it shows the block with id="block-1". When I click on button "4", the block with id="block-4" shows and previous block #block-1 hides. I tried using different ID's because I don't know any other solution to show blocks with different content inside. Unfortunately, my current code doesn't work properly: it toggles the right class to show the div, but I can't hide the previous div or change the block once the button with number is clicked. On the default state, when the page is loaded, the first block (#block-1) should always be visible. Here's the link to codepen with the result: https://codepen.io/tomavl/pen/vYRLJVY

  <button class="filter-btn active" id="1">1</button>
  <button class="filter-btn" id="2">2</button>
  <button class="filter-btn" id="3">3</button>
  <button class="filter-btn" id="4">4</button>

Block 1

Block 2

Block 3

Block 4

  background-color: red;
  color: white;
}

.block-card {
  display: none;
}

.block-card.active {
  display: block;
}

var filterBtn = document.querySelectorAll(".filter-btn");
for (var i = 0; i < filterBtn.length; i++) {
  filterBtn[i].onclick = function () {
    if (this.classList) {
      for (var j = 0; j < filterBtn.length; j++) {
        filterBtn[j].classList.remove("active");
      }
      this.classList.add("active");
    } else {
      this.active += " " + active;
    }
  };
}

$("#2").on("click", function (e) {
  e.stopImmediatePropagation();
  if ($(this).hasClass("active")) {
    $(".block-2").addClass("active");
  } else {
    $(".block-2").removeClass("active");
  }
});

$("#3").on("click", function (e) {
  e.stopImmediatePropagation();
  if ($(this).hasClass("active")) {
    $(".block-3").addClass("active");
  } else {
    $(".block-3").removeClass("active");
  }
});

$("#4").on("click", function (e) {
  e.stopImmediatePropagation();
  if ($(this).hasClass("active")) {
    $(".block-4").addClass("active");
  } else {
    $(".block-4").removeClass("active");
  }
});

A: You can achieve what you need with much less code by using common classes to group content by behaviour. You can use data attributes where required to store custom metadata in an element.
In the following example all buttons use the same event handler. The differences come simply from the data attribute on the button used to change the selector. The code just removes the active class from all relevant elements before applying it to the target.

let $blocks = $('.block-card');

$('.filter-btn').on('click', e => {
  let $btn = $(e.target).addClass('active');
  $btn.siblings().removeClass('active');

  let selector = $btn.data('target');
  $blocks.removeClass('active').filter(selector).addClass('active');
});
body {
  background-color: red;
  color: white;
}

.block-card {
  display: none;
}

.block-card.active {
  display: block;
}

  <button class="filter-btn active" data-target="#block-1">1</button>
  <button class="filter-btn" data-target="#block-2">2</button>
  <button class="filter-btn" data-target="#block-3">3</button>
  <button class="filter-btn" data-target="#block-4">4</button>

Block 1

Block 2

Block 3

Block 4


text:
Q: Selecting columns using ends_with helper and a vector of string names I have a data frame, in wide format, with each column representing one questionnaire item for one particular version of a questionnaire for a particular time point (repeated measures design).
My data would look something like the following:
df <- data.frame(id = c(1:5), t1_QOL_child_Q1 = c(5, 3, 6, 2, 7), t1_QOL_child_Q2 = c(5, 2, 3, 7, 1), t1_QOL_child_Q3 = c(7, 7, 6, 2, 5), t1_QOL_child_joy = c(9,9, 5, 3, 6), t1_QOL_teen_Q1 = c(5, 3, 6, 2, 7), t1_QOL_teen_Q2 = c(5, 2, 3, 7, 1), t1_QOL_teen_Q3 = c(7, 7, 6, 2, 5), t1_QOL_teen_joy = c(5, 7, 4, 7, 9), t1_QOL_adult_Q1 = c(5, 3, 6, 2, 7), t1_QOL_adult_Q2 = c(5, 2, 3, 7, 1), t1_QOL_adult_Q3 = c(7, 7, 6, 2, 5), t1_QOL_adult_joy = c(6, 5, 3, 3, 2), t2_QOL_child_Q1 = c(5, 3, 6, 2, 7), t2_QOL_child_Q2 = c(5, 2, 3, 7, 1), t2_QOL_child_Q3 = c(7, 7, 6, 2, 5), t2_QOL_child_joy = c(9,9, 5, 3, 6), t2_QOL_teen_Q1 = c(5, 3, 6, 2, 7), t2_QOL_teen_Q2 = c(5, 2, 3, 7, 1), t2_QOL_teen_Q3 = c(7, 7, 6, 2, 5), t2_QOL_teen_joy = c(5, 7, 4, 7, 9), t2_QOL_adult_Q1 = c(5, 3, 6, 2, 7), t2_QOL_adult_Q2 = c(5, 2, 3, 7, 1), t2_QOL_adult_Q3 = c(7, 7, 6, 2, 5), t2_QOL_adult_joy = c(6, 5, 3, 3, 2))

For example, column t1_QOL_child_Q1 would mean Question 1 (Q1) of the child version (child) of Quality of Life (QOL) questionnaire, with time point 1 (t1) data.
I want to select only subscales/columns whose suffix are labelled differently. In the sample data above, it would be the columns ending with "joy".
I have over 3000 columns and many more suffixes and it would be a pain to use the following:
select(df, ends_with("joy"), ends_with(<another suffix>), ends_with(<another suffix>))

I have thought of putting all the potential suffixes in a string vector, and use the vector as an input to the ends_with function, but ends_with could only take a single string instead of a vector of strings.
I have searched on Stackoverflow and found a solution that could accommodate a small vector of strings, which is the following:
select(df, sapply(vector_of_strings, starts_with))

However, I have too many suffixes in my vector of strings and the following error message resulted from it: Error: sapply(vector_of_strings, ends_with) must resolve to integer column positions, not a list
Help appreciated. Thanks!

A: We can use a single matches with multiple patterns separated by | to match substrings at the end ($) of the string
df %>%
    select(matches("(joy|Q2)$"))


text:
Q: node-postgres: Postgres client still connected after client.end()? I have a simple connection to my postgres database with node-postgres as shown here:
let { Pool, Client } = require("pg");

let postgres = new Client({
  host: "localhost",
  port: 5432,
  user: "postgres",
  password: "Thisisngo1995!",
});

module.exports = postgres;

I test the connection by touching the endpoint with this code:
let postgres = require("../../databases/postgres");

exports.postgres_get_controller = (req, resp) => {
  console.log("Reached Here");

  postgres
    .connect()
    .then(() => console.log("connected"))
    .catch((err) => console.error("connection error", err.stack))
    .then(() =>
      postgres.end((err) => {
        console.log("postgres disconnected");
      })
    );

I get the desired console.log's signifying that the client was connected, and then disconnected. However, whenever I refresh the page I get this message:

Why does this happen?

A: Clients are not reusable. This changes the client to raise errors whenever you try to reconnect a client that's already been used. They're cheap to create: just instantiate a new one (or use the pool)
See this comment and this issue
The solution is to create the pg client for each request.
ccontroller.js:
let { Client } = require('pg');

exports.postgres_get_controller = (req, resp) => {
  console.log('Reached Here');
  let postgres = new Client({
    host: 'localhost',
    port: 5430,
    database: 'node-sequelize-examples',
    user: 'testuser',
    password: 'testpass',
  });

  postgres
    .connect()
    .then(() => console.log('connected'))
    .catch((err) => console.error('connection error', err.stack))
    .then(() =>
      postgres.end((err) => {
        console.log('postgres disconnected');
        if (err) {
          console.log('error during disconnection', err.stack);
        }
      }),
    );

  resp.sendStatus(200);
};

server.js:
const express = require('express');
const { postgres_get_controller } = require('./controller');

const app = express();
const port = 3000;
app.get('/', postgres_get_controller);

app.listen(port, () => console.log('server start'));

The logs after refreshing the page multiple times to hit the endpoint and executing the controller code:
server start
Reached Here
connected
postgres disconnected
Reached Here
connected
postgres disconnected
Reached Here
connected
postgres disconnected
Reached Here
connected
postgres disconnected
Reached Here
connected
postgres disconnected
Reached Here
connected
postgres disconnected
Reached Here
connected
postgres disconnected


text:
Q: Remote jmeter-server sends all output to controlling jmeter instance My workplace is connected via cable internet with limited up/downstream, so for load-testing a web application I am using a distributed approach:

*

*An instance of jmeter-server (v2.4) is running on a remote linux box which has proper internet connectivity.

*The controlling jmeter GUI (also 2.4) is running on my desktop.

*The two are connected via a VPN.

*The SUT is a web-application hosted in another datacenter.

This works fine - I am able to start the remote thread execution from the jmeter GUI and receive live results in the Summary Report.
The weird part is that my ability to put real load on the SUT is limited by my local internet connection (inbound, downstream). Tracing the link between the local jmeter GUI and the remote jmeter-server, I can see that all HTTP-traffic from SUT towards jmeter-server is sent to the local jmeter GUI. So if the jmeter-server is retrieving a 1MB file from the SUT, it's then sending it to my local jmeter GUI (over my slow internet link).
Is that how it should be? I was expecting that only the key measurements would be transported (success, latency, etc).
[PS: I know I can scp my testplan across to the remote box and run it in a headless jmeter. But then I don't see live results...]

A: This is probably because you are having a "View Tree Results" in your jmeter script. This tells the server to send all responses back to the master so you can view them. That will quickly fill your bandwith and is memory intensive. Try to disable all listeners in your script and only have the "View Aggregate results" one in there.
With high load, you're not interested in individual results. There is also no need to open up your firewall in your datacenter if you use ssl tunneling. I've documented that in a blogpost because I couldn't find a simple step-by-step online, you might want to check that out too at http://rolfje.com/2012/02/16/distributed-jmeter-through-vpn-and-ssl/

A: I would recommend you to write your results to a file. Before doing so, you can optionally perform a select / deselect of result save configuration by clicking on configure button and/or by checking write success/error to log.  By unselecting result sampler data, save response messages etc you can reduce the amount of data being sent to your console.

A: I THINK the way you have it set up, both the Local instance of Jmeter and the remote are running the script at the same time, hence traffic is being directed to your local box.
What I've found to be more effective is to remote INTO the machine running JMeter.  Everything is then local to the proper machine, and I don't have to worry about bottle necks.
I would recommend having a simple data writer element that saves to a file on the REMOTE linux box.
In the GUI, you could still have just the aggregate report to keep an eye on what's happening.
Hope this helps.  If not, I would recommend posting to the JMeter user group:
http://jmeter.512774.n5.nabble.com/


text:
Q: PHP drop-down list with main item as optgroup and child item as option I try to create a drop-down list from a database that contains the main items and their child items. I want the main items to become optgroup labels and the child items the option items.
<select>
  <optgroup label="$rs_pa['Name']">
    <option value="$rs_ch['Link']">$rs_ch['Name']</option>
    <option value="$rs_ch['Link']">$rs_ch['Name']</option>
  </optgroup>
  <optgroup label="$rs_pa['Name']">
    <option value="$rs_ch['Link']">$rs_ch['Name']</option>
    <option value="$rs_ch['Link']">$rs_ch['Name']</option>
  </optgroup>
</select>

The above is just a scheme to show where each variable should fit..
$rs_pa['Name] - is the name of the parent item.
$rs_ch['Name] - is the name of the child item.
$rs_ch['Link'] - is the link of the child item.
This is the code I have right now:
$mysql_table_items      = "sys_menu_top";
$mysql_table_options    = "sys_options";

// SQL QUERY
$mysql_result_number    = mysql_query("SELECT VALUE FROM $mysql_table_options WHERE Name LIKE 'nav_menu_elements_on_line_usr'") or die($myQuery . "

" . mysql_error());
$mysql_select_parent    = "SELECT * FROM $mysql_table_items WHERE `Parent` = '0' AND Type LIKE 'top' AND Active = 1 ORDER BY `Order` ASC";
$mysql_select_child     = "SELECT * FROM $mysql_table_items WHERE `Parent` = '" . $rs_pa['ID'] . "' AND Active = 1 ORDER BY `Order` ASC";

// SQL RESULT
$mysql_result_number    = mysql_fetch_array($mysql_result_number, MYSQL_ASSOC) or die("Error: Query Failed! " . mysql_error());
$mysql_result_parent    = mysql_query($mysql_select_parent) or die("Error: Query Failed! " . mysql_error());
$mysql_result_child     = mysql_query($mysql_select_child) or die("Error: Query Failed! " . mysql_error());

$output .= "<select>";
while ($rs_pa = mysql_fetch_array($mysql_result_parent)) {
    $output .= "<optgroup label='" . $rs_pa['Name'] . "'>";
    while ($rs_ch = mysql_fetch_array($mysql_result_child)) {
        $output .= "<option value='" . $rs_ch['Link'] . "'>" . $rs_ch['Name'] . "</option>";
        }
    $output .= "</optgroup>";
    }

$output .= "</select>";

echo $output;

The prblem is that this doesn't show right.. I tried everything but I am not so good with php.. Thank you for any help..

A: You are referencing to $rs_pa['ID'] on this line:
$mysql_select_child     = "SELECT * FROM $mysql_table_items WHERE `Parent` = '" . $rs_pa['ID'] . "' AND Active = 1 ORDER BY `Order` ASC";

Are you sure $rs_pa['ID'] is defined at that point?
Something like this should work better:
$mysql_table_items      = "sys_menu_top";
$mysql_table_options    = "sys_options";

// SQL QUERY
$mysql_result_number    = mysql_query("SELECT VALUE FROM $mysql_table_options WHERE Name LIKE 'nav_menu_elements_on_line_usr'") or die($myQuery . "

" . mysql_error());
$mysql_select_parent    = "SELECT * FROM $mysql_table_items WHERE `Parent` = '0' AND Type LIKE 'top' AND Active = 1 ORDER BY `Order` ASC";

// SQL RESULT
$mysql_result_number    = mysql_fetch_array($mysql_result_number, MYSQL_ASSOC) or die("Error: Query Failed! " . mysql_error());
$mysql_result_parent    = mysql_query($mysql_select_parent) or die("Error: Query Failed! " . mysql_error());

$output = "<select>";

while ($rs_pa = mysql_fetch_array($mysql_result_parent))
{
    $output .= "<optgroup label='" . $rs_pa['Name'] . "'>";

    $mysql_select_child     = "SELECT * FROM $mysql_table_items WHERE `Parent` = '" . $rs_pa['ID'] . "' AND Active = 1 ORDER BY `Order` ASC";
    $mysql_result_child     = mysql_query($mysql_select_child) or die("Error: Query Failed! " . mysql_error());

    while ($rs_ch = mysql_fetch_array($mysql_result_child))
    {
        $output .= "<option value='" . $rs_ch['Link'] . "'>" . $rs_ch['Name'] . "</option>";
    }

    $output .= "</optgroup>";
}

$output .= "</select>";

echo $output;

Some further improvements could be made:

*

*Stop using mysql_query and switch to PDO (http://php.net/manual/en/ref.pdo-mysql.php) which is more secure. The mysql_query functions are deprecated starting from PHP 5.5.0 anyway.

*Rewrite your query to fetch all the data you need in a single query. This will really speed up things.

*Separate your PHP from your HTML by using templates.


text:
Q: Invalid Identifier SQL coursework I am currently working on some SQL coursework, this is my code so far:
CREATE TABLE VEHICLES
  (
     Vehicle_id            VARCHAR(6)  PRIMARY KEY NOT NULL,
     Vehicle_Make          VARCHAR(18),
     Vehicle_Model         VARCHAR(25),
     Passenger_Number      INT,
     Number_Owned          INT,
     Registration_Date     DATE, NOT NULL UNIQUE
     Colour                VARCHAR(10),
     Rate                  INT
  );

Each time I try and run the statement it gives me

SQL ERROR: ORA-00904: invalid identifier

A: You have a comma at the wrong place.
Here it is corrected:
CREATE TABLE VEHICLES
  (
     Vehicle_id            VARCHAR(6)  PRIMARY KEY NOT NULL,
     Vehicle_Make          VARCHAR(18),
     Vehicle_Model         VARCHAR(25),
     Passenger_Number      INT,
     Number_Owned          INT,
     Registration_Date     DATE NOT NULL UNIQUE,
     Colour                VARCHAR(10),
     Rate                  INT
  );


text:
Q: Setting the Facebook Profile picture as a ImageView in a ListView I got this app that records the user's Facebook ID in a MySQL table, and now I'm trying to get this ID and show the user's profile picture on a ListView, but I don't know what I'm doing wrong.
My custom ArrayAdapter:
public class VisualAdapter extends ArrayAdapter<String> {

private final Context contexto;

private final String[] comics, username, userid;

URL img_url = null;

Bitmap bm;

public VisualAdapter(Context contexto, String[] comics, String[] username,
        String[] userid) {
    super(contexto, R.layout.exibeimg, comics);
    this.contexto = contexto;
    this.comics = comics;
    this.username = username;
    this.userid = userid;
}

public View getView(int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub
    LayoutInflater inflater = (LayoutInflater) contexto
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    View rowView = inflater.inflate(R.layout.exibeimg, parent, false);
    TextView textView = (TextView) rowView.findViewById(R.id.tvTitleImage);
    ImageView imageView = (ImageView) rowView.findViewById(R.id.ivImageVisual);
    ImageView ivUser = (ImageView) rowView.findViewById(R.id.ivUser);
    TextView tvUser = (TextView) rowView.findViewById(R.id.tvUserNAME);
    textView.setText(comics[position]);
    tvUser.setText(username[position]);

    try {
        img_url = new URL("http://graph.facebook.com/"+userid+"/picture?type=thumbnail");
        bm = BitmapFactory.decodeStream(img_url.openConnection().getInputStream());
        ivUser.setImageBitmap(bm);
    }
    catch (Exception e) {
        e.printStackTrace();
    }
    return rowView;
}

}

Logcat: http://pastebin.com/kmLXKvZJ
Also, this is inside a tab. It's in Tab 2, and when the app starts at Tab 1 when I click in Tab 2 (to see this list), it takes a few seconds to load, is there something that I can do to load it faster?

A: It is taking a few seconds to load because you are performing a network operation synchronously inside getView(), which blocks the main UI thread from rendering the view every single time when it is waiting for a network response.  This is very bad and what you need to do is to do an asynchronous lazy loading of images so that downloading the pictures is not performed on the UI thread.
Read this great article on how to implement ListView correctly so that it does not take a few seconds to load.


text:
Q: Rest Template response body is 404 but Status as 500 I have written a Rest template to call another Rest service Get by id Method.
When i hit URL localhost:8080/v1/{UUID} with invalid Id.
public void test(UUID someId) {
    restTemplate.getForObject("localhost:8080/v1/"+id, String.class);
}

I am getting body as 404 but Status as 500 Internal Server Error.
I am not sure to handle exception inside method and throw Resource not found exception. Because response is getting from another service[valid 404 for invalid id].
In my service it is 500 because of Null response from above URL.
Could anyone please suggest best practice to handle validations or exceptions in Rest template.


text:
Q: My javascript popup shows for a split second if there's a cookie I have no clue what I'm doing wrong. It works it just shows the popup for a split second. Would a timeout option be better? Which part is the problem? I'm a little new to Javascript so I don't really know what to exactly look for.

<body onLoad="checkCookie('MyCookie')"

A: If your goal is to have the element with id="google" to be hidden from the very beginning of the page display (so it never shows), then you should add a CSS rule that loads in the head section like this:
#google {display: none;}

Or, you should add a style element to the HTML itself:

As your code is currently written, it sounds like it is doing what it is supposed to.  It waits for the entire document to be loaded (including images) and then it hides the element with id="google".  That means the item will show briefly while the page is loading and then your code will hide it.
If you can't modify the CSS or the HTML for the google object and you're just trying to hide it as soon as possible with javascript and the google object is present in the HTML of your page (not added programmatically), then you can do this:

other HTML here

This will at least not wait for all images to load before hiding it.

A: I fixed it like this:
Create a css property of display:none; for #google
#google{display:none;}

Then switch around the last portion of code to display only if they don't have the cookie, and to create the cookie.
/** Check if cookie exists else create a new one. **/
function checkCookie(name) {
    if (readCookie(name)) {

    }
    else document.getElementById('google').style.display = "inline";
         document.getElementById('google').style.visibility = "visibility";
         createCookie(name,"cookie 4 the day",1);

In case anyone runs into this problem. Worked great for me.


text:
Q: Finding text not present in a string As you can see I have two variables defined: a variable named href which has multiple links as one string and a variable named text, now in text I have the links that I have already visited/downloaded from. I want Python to print the text that is present in href but not in text.
So I imagine its using a for loop?
When I execute single letters get returned, all separated on a different line.
import requests
from bs4 import BeautifulSoup

url = 'amazon.com'
source_code = requests.get(url)
plain_text = source_code.text
soup = BeautifulSoup(plain_text, 'html.parser')

for link in soup.findAll('a', {'class': 'gridItem-trackInfo-title-anchor'}):
    href = link.get('href')

    file = open('file.txt', 'r')
    text = file.read()
    file.close

    for i in href:
        if i not in text:
            print(i)

A: If you just want the input on a single line, use print(i, end='') and you should be ok.

If you want links you should do
for i in links(href):
    if i not in links(text):
        print(i)

Where the links function may be found at retrieve links from web page using python and BeautifulSoup

If you want links and not letters use:
    if link not in text:
        print(link)

Before you were looping over the letters of each link.
Instead of:
for i in href:
    if i not in text:
        print(i)

A: It seems that href is a string and you are iterating over it. Is this code any better ?
import requests
from bs4 import BeautifulSoup

url = 'amazon.com'
source_code = requests.get(url)
plain_text = source_code.text
soup = BeautifulSoup(plain_text, 'html.parser')

file = open('file.txt', 'r')
text = file.read()
file.close()

for link in soup.findAll('a', {'class': 'gridItem-trackInfo-title-anchor'}):
    href = link.get('href')

    if href not in text:
        print(href)


text:
Q: Render React Site in a DIV We have site built in react that our client calls (url) and load in a iFrame. We need a mechanism so that the clients can load site in a DIV tag.
We want to provide the HTML/Javascript for our clients (in HTML/Vanilla JavaScript) so that embed our site in a DIV tag rather than iFrame.
Thanks
Sri


text:
Q: Instagram API - How to Subscribe to a specific User I am trying to use the Instagram-API to subscribe to a user so that when that user posts anything on Instagram, then my app will receive a POST. I have set up the app in the sandbox, defined the callback URIs, added my user to the Sandbox, then called the following url to register a subscription;
https://api.instagram.com/v1/subscriptions?client_id=MY_CLIENT_ID&client_secret=MY_CLIENT_SECRET&object=user&user_id=jonlees1234&aspect=media&verify_token=1234567890&callback_url=https://instagram.pulselive.com/SubscriptionCallback
The part of that URL that I am unclear about is the following;
&object=user&user_id=jonlees1234&aspect=media
I have a GET and POST method on my Callback Url so that when the SubscriptionValidation GET is called the hub.challenge is echoed. I have tested this and it works. However, the response I get from the above URL is as follows;
{"meta":{"code":200},"data":[]}

This indicates that all is working, but that there are no subscriptions when I run the list of subscriptions api call.
What could I be missing?

A: Ok, I finally I found the answer.
https://api.instagram.com/v1/subscriptions?client_id=MY_CLIENT_ID&client_secret=MY_CLIENT_SECRET&object=user&id=3111490094&aspect=media&verify_token=THE_USERS_ACCESS_TOKEN&callback_url=http://instagram.pulselive.com/SubscriptionCallback
The KEY issue was that I was using the username and I SHOULD have been using the user id, as follows;
&object=user&id=1234567890&aspect=media
All working now.


text:
Q: Salesforce app license conversion We have a Salesforce application which is being listed at Appexchange, and we are providing trial of 45 days, many of the clients are using the application and for some trial period has been finished but they want to continue, so they can become the active user of our app.
For developer perspective, we are managing LMO at our organization and we can see the license has been expired for their org. Many documentation of Salesforce says that, we can change the License type from trial to active, but was not able to do even when we logged through License Manager credentials.
So In short I want help at two points.

*

*If we want to extend license for particular org, How can we do that
from LMO?

*How can a customer himself expect to convert his license    from
trial to active, without loosing the application data?

A: I believe You Should  Use the License Management App (LMA) to apply licensing to your managed package to control how many users in the
installer's organization can access your package and for how long. Every time your package is installed, a lead record is created
in the LMA.
For more details Refer to the following link

*

*http://www.salesforce.com/docs/en/lma/salesforce_lma_guide.pdf
Regards
Anchal Garg


text:
Q: What arguments does new take? Does new in C++ call a constructor behind the scenes? Or is it the other way around?
I have seen code like new MyClass(*this) which confuses me, since I didn't know that new could take arguments.
Maybe that's because new can call a constructor and, as a result, it can take the arguments declared by a constructor?

A: MyClass(*this) creates an object of type MyClass by calling its constructor and passing *this as an argument. Putting new behind it means the object is allocated on the heap instead of the stack. It's not new which is taking the argument, it's MyClass.

A: There is a difference between new and operator new.
The new operator uses a hidden operator new function to allocate memory and then it also "value-initializes" the object by calling its constructor with the parameters after the class name.
In your case you call new which allocates memory using ::operator new() and then it initializes an object of MyClass class in that memory using a constructor with the parameter *this.
#include <iostream>

class A {
    public:
        int m_value;
        A(int value): m_value(value){};
};

int main (){

    int *a  = new int;

    auto b= new A(1);

    std::cout << *a << std::endl;
    std::cout << b->m_value << std::endl;
    printf("%02x ", *b);

}

Program returned:
0
15
0f

As you can see, the new for the a variable creates only a pointer that is value-initialized to 0. That's why when we dereference it we have 0 (all bit all 0, int is 4 bytes most of the time and the pointer point to a memory content = to 0x0000)
But for the b variable we pass parameters. And if we look at the memory content of the b object we can read 0f which means it contains 15 (the member value)

A: This is not new taking arguments, it's the constructor taking arguments.


text:
Q: how do I get the form data in a javascript object so I can send it as the data parameter of an $.ajax call How to return json after form.submit()?

 <form id="NotificationForm" action="<%=Url.Action("Edit",new{Action="Edit"}) %>" method="post" enctype="multipart/form-data" onsubmit='getJsonRequestAfterSubmittingForm(this); return false;'>
      <%Html.RenderPartial("IndexDetails", Model);%>
     </form>

 $.ajax({
        url: '<%=Url.Action("Edit","Notification") %>',
        type: "POST",
        dataType: 'json',
        data: $("#NotificationForm").submit(),
        contentType: "application/json; charset=utf-8",
        success: function(result) {
            if (result.Result == true) {
                alert("ghjghsgd");
            }
        },
        error: function(request, status, error) {
            $("#NotSelectedList").html("Error: " & request.responseText);
        }

    });

A: I guess what you're actually looking for is not the Submit method, but how to serialise the form data to a json object. To do this you have to use a helper method like here: Serialize form to JSON
Use this instead of running the submit() method, and you'll be fine.
Also, this question is a duplicate of this (even though the question text, and the title are completely misleading): Serialize form to JSON with jQuery
Posting the jQuery extender, just in case, so that it doesn't get lost :)
$.fn.serializeObject = function()
{
   var o = {};
   var a = this.serializeArray();
   $.each(a, function() {
       if (o[this.name]) {
           if (!o[this.name].push) {
               o[this.name] = [o[this.name]];
           }
           o[this.name].push(this.value || '');
       } else {
           o[this.name] = this.value || '';
       }
   });
   return o;
};

After you have this in your page, you can update your ajax call with this:
$.ajax({
        url: '<%=Url.Action("Edit","Notification") %>',
        type: "POST",
        dataType: 'json',
        data: $("#NotificationForm").serializeObject(),
        contentType: "application/json; charset=utf-8",
        success: function(result) {
            if (result.Result == true) {
                alert("ghjghsgd");
            }
        },
        error: function(request, status, error) {
            $("#NotSelectedList").html("Error: " & request.responseText);
        }

    });

UPD: If you want to POST the form, then get the response as a json object, and do another ajax call.. then you should look at the jquery.form plugin. you will be able to post your form using an ajax call, then get the response, and run some js when it will return.


text:
Q: How to Get Channel id or url after Google Oauth PHP i am trying to code an application system with youtube login. but i have an issue After i get required authorisation with oauth 2.0 i want to get choosen youtube channel id in a string but i could not do it can somebody please help me.
    $client = new Google_Client();
    $client->setClientId($client_id);
    $client->setClientSecret($client_secret);
    $client->setRedirectUri($redirect_uri);
    $client->setApplicationName("BYTNETWORK");
    $client->setScopes(array('https://www.googleapis.com/auth/userinfo.profile',
     'https://www.googleapis.com/auth/yt-analytics.readonly'

      ));

if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
  $client->setAccessToken($_SESSION['access_token']);
} else {
  $authUrl = $client->createAuthUrl();
}

so after this i want a string like
$channelid = "xxxxx"; to use it in code below
$data = file_get_contents('http://gdata.youtube.com/feeds/api/users/$channelid?alt=json');
$data = json_decode($data, true);
$stats_data = $data['entry']['yt$statistics'];
$medya = $data['entry']['media$thumbnail'];
//yt$username kısmından kanal adı parse edilir

/**********************************************************/
echo "
";
echo "Subscribers: $stats_data[subscriberCount]
";
echo "Views: $stats_data[totalUploadViews]
";

A: Using OAUTH 2, you can get a refresh_token and an access_token for the requested scope(s).
If you want to get the YouTube channel-id, for an authorized user, using his access_token, then you send the request:
https://www.googleapis.com/youtube/v3/channels?part=id&mine=true&access_token=HereYourAccessToken

In the request above you need to replace the string "HereYourAccessToken".
The respone is a JSON string. And the channel-id is in the field named: items['id'] (or items.id).
Note, that an access_token expires after 1 hour. If so, then use the refresh_token to obtain a new one,
The refresh_token is valid until revoked by the owner.


text:
Q: How to write proper big data loader to sqlite I`m trying to write loader to sqlite that will load as fast as possible simple rows in DB.
Input data looks like rows retrieved from postgres DB. Approximated amount of rows that will go to sqlite: from 20mil to 100mil.
I cannot use other DB except sqlite due to project restrictions.
My question is :
what is a proper logic to write such loader?
At first try I`ve tried to write set of encapsulated generators, that will take one row from Postgres, slightly ammend it and put it into sqlite. I ended up with the fact that for each row, i create separate sqlite connection and cursor. And that looks awfull.
At second try , i moved sqlite connection and cursor out of the generator , to the body of the script  and it became clear that i do not commit data to sqlite untill i fetch and process all 20mils records. And this possibly could crash all my hardware.
At third try I strated to consider to keep Sqlite connection away from the loops , but create/close cursor each time i process  and push one row to Sqlite. This is better but i think also have some overhead.
I also considered to play with transactions : One connection, one cursor, one transaction and commit called  in generator each time row is being pushed to Sqlite. Is this i right way i`m going?
Is there some widely-used pattern to write such a component in python? Because I feel as if I am inventing a bicycle.

A: SQLite can handle huge transactions with ease, so why not commit at the end? Have you tried this at all?
If you do feel one transaction is a problem, why not commit ever n transactions? Process rows one by one, insert as needed, but every n executed insertions add a connection.commit() to spread the load.

A: *

*See my previous answer about bulk and SQLite. Possibly my answer here as well.

*A question: Do you control the SQLite database? There are compile time options you can tweak related to cache sizes, etc. you can adjust for your purposes as well.

In general, the steps in #1 are going to get you the biggest bang-for-your-buck.

A: Finally i managed to resolve my problem. Main issue was in exessive amount of insertions in sqlite. After i started to load all data from postgress to memory, aggregate it proper way to reduce amount of rows,  i was able to  decrease processing time from  60 hrs to 16 hrs.


text:
Q: java pass by value primitive vs objects I have read the forum and gone through some links and found that Java is all pass by value and i think i do understand that to how the references thing work but not how primitives work. It is said that for both primitives and object, pass by value works in the same manner.
I created a sample program
public class BirthDate {
int lear;
int year; // Instance variable
public static void main(String [] args) {
    BirthDate bd = new BirthDate();
    bd.lear=200;
    bd.year=300;
    int a=56;
    bd.showYear(a,bd);
    System.out.println(a);
    System.out.println(bd.lear);
}
public void showYear(int a, BirthDate bd) {
        a=59;
        System.out.println(bd.lear);
        bd.lear=400;
        System.out.println(bd.lear);
        System.out.println(a);
}

}
Output of the above program is 200
400
59
56
400
Now, if the bits were passed in case of both primitives and reference then why the change in  reference value in showYear method reflected the change in original bd object (value changed to 400) and not a primitive data type i.e. a.
Can anyone please suggest?

A: You pass the reference of the BirthDate by value, so your method refers to the same BirthDate as in your main method.
However you then change the member of that object (lear) from 200 to 400.
Because you've passed the reference to the original object, it's not been copied and you're dealing with the same object at all times.

A: When you are passing BirthDate bd you are passing a reference to this object.
If in your show year you will do:
public void showYear(int a, BirthDate bd) {
        bd = new BirthdayDate();
}

This bd = new BirthdayDate(); is equivalent to a= 59; in the nature. This is important to understand.
You are not going to change the bd outside of it- you are just reassigning different reference.
However your:
bd.lear=400;

Accesses the object that is pointed by this reference and changes its value. This way you are editing an object. This can also be seen as just an assignment of a primitive- but it happens inside the place that is pointed by bd.

A: They are all pass by value. For reference, object reference is passed by value. When you say-
bd.showYear(a,bd);

You are passing the address of the bd to showYear method. Let's break it down-
BirthDate bd = new BirthDate(); // Let's say a new object bd is created at address 10.

I changed the parameter bd to bd2 below so we wouldn't mistake it with the Brithday bd above
public void showYear(int a, BirthDate bd2) { // Parameter bd2 is pointing to address 10

    bd2.lear=400; // bd2 followed the address 10 and changed bd's leap property. This doesn't change the fact that bd still is at address 10.
}

A: You can change in a method the fields of the Object, which the reference refers to, but you cannot reassign it to another Object. Primitives are though "immutable" and you cannot change their value in a method. That is the way java parameters behave in a method.

A: In both cases you are passing value only. U pass the value of Object ID into new reference Variable bd which is local in that case.
So when u call
     bd.lear=400;

it changes the value of lear variable of the Object.
Now when function finishes , stack is destroyed. So is reference variable bd.
But since main function bd contains id of the object , object is not destroyed.
Coming to primitive type , u changed the value of local variable a of showYear function in this
   a=59;

it prints it and is destroyed with stack of the object. But main functions local variable is still present with value 56.
Make a part of Object and then try
  bd.a=59;

you will see value changing. Read about Local variables, instance variables and class variables..!


text:
Q: How to add a custom button to the grapesjs toolbar? How do you add a custom button to the grapesjs toolbar?
I have followed the instructions on this github issue and written the code below, but the button doesn't appear in the toolbar as expected.
What am I missing?
initToolbar() {
        const { em } = this;
        const model = this;
        const ppfx = (em && em.getConfig('stylePrefix')) || '';

        if (!model.get('toolbar')) {
            var tb = [];
            if (model.collection) {
                tb.push({
                    attributes: { class: 'fa fa-arrow-up' },
                    command: ed => ed.runCommand('core:component-exit', { force: 1 })
                });
            }
            if (model.get('draggable')) {
                tb.push({
                    attributes: {
                        class: `fa fa-arrows ${ppfx}no-touch-actions`,
                        draggable: true
                    },
                    //events: hasDnd(this.em) ? { dragstart: 'execCommand' } : '',
                    command: 'tlb-move'
                });
            }
            if (model.get('schedule')) {
                tb.push({
                    attributes: { class: 'fa fa-clock', },
                    command: 'tlb-settime'
                });
            }
            if (model.get('copyable')) {
                tb.push({
                    attributes: { class: 'fa fa-clone' },
                    command: 'tlb-clone'
                });
            }
            if (model.get('removable')) {
                tb.push({
                    attributes: { class: 'fa fa-trash-o' },
                    command: 'tlb-delete'
                });
            }
            model.set('toolbar', tb);
        }
    },

A: One way to add new toolbar icons is to add the button as each component is selected.
  // define this event handler after editor is defined
  // like in const editor = grapesjs.init({ ...config });
  editor.on('component:selected', () => {

    // whenever a component is selected in the editor

    // set your command and icon here
    const commandToAdd = 'tlb-settime';
    const commandIcon = 'fa fa-clock';

    // get the selected componnet and its default toolbar
    const selectedComponent = editor.getSelected();
    const defaultToolbar = selectedComponent.get('toolbar');

    // check if this command already exists on this component toolbar
    const commandExists = defaultToolbar.some(item => item.command === commandToAdd);

    // if it doesn't already exist, add it
    if (!commandExists) {
      selectedComponent.set({
        toolbar: [ ...defaultToolbar, {  attributes: {class: commandIcon}, command: commandToAdd }]
      });
    }

  });

If it's important to you that only components with the "schedule" attribute have this toolbar option show up, as in your example, you can access and check this from selectedComponent:
const selectedComponent = editor.getSelected();
const defaultToolbar = selectedComponent.get('toolbar');
const commandExists = defaultToolbar.some(item => item.command === commandToAdd);

// add this
const hasScheduleAttribute = selectedComponent.attributes.schedule;

if (!commandExists && hasScheduleAttribute) { // ...set toolbar code


text:
Q: selenium.common.exceptions.WebDriverException: Message: unknown error: Chrome failed to start: exited abnormally. Dockerize Flask Application I have been trying for over a week to dockerize a Flask application with the MongoDB database. My application has the following structure:
aplication
   - db
     Dockerfile
   - web
     app.py
     Dockerfile
     requirements.txt
   docker-compose.yml

This application makes web scraping using the selenium, selenium-requests and BeautifulSoup libraries. The problem I've been getting for a week is:
selenium.common.exceptions.WebDriverException: Message: unknown error: Chrome failed to start: exited abnormally.
  (unknown error: DevToolsActivePort file doesn't exist)
  (The process started from chrome location /usr/bin/google-chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.)

I've been trying several different ways to make the application's Dockerfile and I can't find one that really works.
My code is as follows:

*

*app.py

from bs4 import BeautifulSoup
from seleniumrequests import Chrome
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from flask import Flask, request, jsonify
from flask_restful import API, Resource
from pymongo import MongoClient

app = Flask(__name__)
api = api(app)

client = MongoClient("mongodb://db:27017")
db = client.FlaskAPI

users = db["users"]

chrome_options = Options()
chrome_options.add_argument("--headless")
webdriver = Chrome(executable_path='/usr/local/bin/chromedriver', options=chrome_options)
webdriver.get(self.url+'login')
webdriver.find_element_by_id("userName-id").send_keys(username)
webdriver.find_element_by_id("passWd-id").send_keys(password)

webdriver.find_element(By.XPATH, '//input[@value="Login"]').click()
soup = BeautifulSoup(self.webdriver.page_source, 'lxml')

data = ''

        p = re.compile('var userParam=(.*);')
        for script in soup.find_all("script", {"src":False}):
            if p.search(script.string):
                data = json.dumps(str(script.string))

data = remove_formatation_elements(data)
users.insert({"data": data})

*

*db Dockerfile

FROM mongo:5.0.3

*

*web Dockerfile

FROM python:3.8

WORKDIR /usr/src/app

# Install Chrome WebDriver
RUN CHROMEDRIVER_VERSION=`curl -sS chromedriver.storage.googleapis.com/LATEST_RELEASE` && \
    mkdir -p /opt/chromedriver-$CHROMEDRIVER_VERSION && \
    curl -sS -o /tmp/chromedriver_linux64.zip http://chromedriver.storage.googleapis.com/$CHROMEDRIVER_VERSION/chromedriver_linux64.zip && \
    unzip -qq /tmp/chromedriver_linux64.zip -d /opt/chromedriver-$CHROMEDRIVER_VERSION && \
    rm /tmp/chromedriver_linux64.zip && \
    chmod +x /opt/chromedriver-$CHROMEDRIVER_VERSION/chromedriver && \
    ln -fs /opt/chromedriver-$CHROMEDRIVER_VERSION/chromedriver /usr/local/bin/chromedriver

# Install Google Chrome
RUN curl -sS -o - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - && \
    echo "deb http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google-chrome.list && \
    apt-get -yqq update && \
    apt-get -yqq install google-chrome-stable && \
    rm -rf /var/lib/apt/lists/*

COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt

COPY . .

CMD ["python", "app.py"]

*

*requirements.txt

flask
flask-restful
pymongo
bs4
selenium
selenium-requests
lxml
webdriver-manager

and

*

*docker-compose.yml

version: '3.9'

services:
  web:
    build: './web'
    ports:
      - '5000:5000'
    links:
      - db

  db:
    build: './db'

With the web folder dockerfile the chromedriver is created in the /usr/local/bin folder and the google-chrome and google-chrome-stable files in the /usr/bin folder.
So I can't understand why, even after so many different attempts, I can't get this code to work...
Could someone help me please?

A: This error message...
selenium.common.exceptions.WebDriverException: Message: unknown error: Chrome failed to start: exited abnormally.
  (unknown error: DevToolsActivePort file doesn't exist)
  (The process started from chrome location /usr/bin/google-chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.)

...implies that the ChromeDriver was unable to initiate/spawn a new WebBrowser i.e. Chrome Browser session.
A common cause for Chrome to crash during startup is running Chrome as root user (administrator) on Linux. While it is possible to work around this issue by passing --no-sandbox flag when creating your WebDriver session, such a configuration is unsupported and highly discouraged. You need to configure your environment to run Chrome as a regular user instead.


text:
Q: Probability that randomly chosen value from one distribution is greater than randomly chosen value from another distribution Say I have $n$ values sampled from two distributions, $A$ and $B$ .  That is, I have a sample $A_1, A_2, \dots, A_n$ and a sample $B_1, B_2, \dots, B_n$.  How would I go about finding $P\left(A_i>B_j\right)$ for any given value $i\in(1,\dots,n)$ and $j\in(i,\dots,n)$?
I know I could get a bootstrapped solution fairly easily using the following code:
bootstrapProcedure <- function(A, B, sample.size = 100) {
  # Calculates the fraction of times a sample of size (sample.size) from A is
  # greater than a sample of the same size from B (both drawn with replacement).
  #
  # Args:
  #   A: vector of values for sample 1
  #   B: vector of values for sample 2
  #   sample.size: integer of the size of the bootstrapped sample to draw
  #
  # Returns:
  #   The fraction of times the sample from A is greater than the sample from B
  mean(sample(A, sample.size, replace = T) > sample(B, sample.size, replace = T))
}

# Draw 2 populations
A <- rnorm(1000, mean = 1, sd = 2)
B <- rnorm(1000, mean = 2, sd = 4)

# Get the bootstrapped probability 1,000 times
replicate(1000, bootstrapProcedure(A, B))

but it seems like there should be a simple, analytical solution to this.  Any ideas how I should go about finding it?

A: Your bootstrap simulation suggests, the A's and B's are independent; I will assume so.
Note that $P(A>B)=P(A-B>0)$.
In the case where A and B are also normal, $D=A-B \sim N(\mu_A-\mu_B,\sigma^2_A+\sigma^2_B)$
In that case
\begin{eqnarray*}
P(D>0) &=& P(\frac{D-\mu_D}{\sigma_D}>\frac{0-\mu_D}{\sigma_D}) \\
&=& P(Z>-\frac{\mu_A+\mu_B}{\sqrt{\sigma^2_A+\sigma^2_B}})=P(Z<\frac{\mu_A+\mu_B}{\sqrt{\sigma^2_A+\sigma^2_B}})\\
&=&\Phi\left(\frac{\mu_A+\mu_B}{\sqrt{\sigma^2_A+\sigma^2_B}}\right)
\end{eqnarray*}
In the case of other distributions there may be no simple "closed" form (you'll get one for a few distributions but you can't expect in in general). For specific instances the value of the probability can be calculated via numerical convolution.
(If you have bivariate normality but not independence, you can do a similar calculation.)

A: Answer: AUC

Probability that randomly chosen value from one distribution is greater than randomly chosen value from another distribution

*

*This an eloquent description of the what the Area Under The Curve is estimating.

Check out the Mann-Whitney-U test if you want a hypothesis-test (as others pointed out). AUC is the standardized and interpretable U-statistica.
If you're into R look at for example pROC if you necessarily need a bootstrapped AUC. For mere AUC-calculation I use the lightweight WeightedROC-package
To use standard packages, organize your data with "labels" as 0 for sample a and 1s for sample b then use the measurements as the "score". AUC is then an estimate for $P\left(A_i<B_j\right)$


text:
Q: Yii2: registerJs() implicitly includes JqueryAsset, how to avoid In Yii2 there is a $this->registerJs() method available in views for registering inline JS. I use it as described in documentation:
$js = "...prepare js code...";
$this->registerJs($js, View::POS_READY);

The problem is that with View::POS_READY (which is the default for second argument) registerJs() implicitly requires yii\web\JqueryAsset (source code).
But I already included Jquery in my own asset bundle - it is all-min.js, there are Jquery + plugins minified and concatenated in a single file. Yii2 includes JqueryAsset, therefore duplicating Jquery on a resulting page.
How do I tell Yii2 that Jquery is already included or avoid this duplication in some other way?

A: You can easily customize jquery asset bundle by configuring assetManager in the application components configuration (usually config/web.php).
You can disable one or multiple asset bundles by associating false with the names of the asset bundles that you want to disable :
    'assetManager' => [
        'bundles' => [
            'yii\web\JqueryAsset' => false,
        ],
    ],

Read more : http://www.yiiframework.com/doc-2.0/guide-structure-assets.html#customizing-asset-bundles


text:
Q: Composite primary key limit? Is it OK if I create a composite primary key from 4 columns? Like:
PRIMARY KEY(name, slug, type, parent)

So there should not be more than one row with the same name, slug, type and parent. Are there too many columns? Will it affect performance?
I'm using sqlite btw.

A: SQLite has a limit of 2000 columns in an index.
The performance of a 4-column index will not be much different from that of a 3-column index.
However, generic performance statement are not interesting.
What matters for you is whether this table structure is performant enough for you, which you can find out only by measuring it.

Please note that if you do lookups on only one column, that column must be the first one in an index to allow the index to be used.

A: It's usually recommended to have an ID field that is unique on its own.  Comparing INTEGER values is faster than comparing strings, so your composite key will affect performance negatively.
Adding a column with the following as the datatype would be ideal if you will be joining to other tables:
 INTEGER PRIMARY KEY AUTOINCREMENT


text:
Q: Convert HH:MM UTC+2 to HH:MM [not UTC] I have a dictionary that contains times, set up like
{ '2018-06-22': { 24: { 24: { 'Team1': 'Nigeria',
                              'Team2': 'Iceland',
                              'Time': '18:00',
                              'Timezone': 'UTC+ ... }}

How can I take the Time and change from whatever zone it's in (UTC+2, UTC, UTC+3, etc) and change to, say, USA Chicago (UTC-5)?
I've tried using the solution here but get 1900-01-01 10:00:00-05:00.  The date is fine, I can remove that. I am not sure why the time though seems to be a range? I was expecting 24 hour format output.
from datetime import datetime
from dateutil import tz

def update_timezone(time, old_zone, new_zone):
    """
    Takes an old timezone and converts to the new one
    """
    from_zone = tz.gettz(old_zone)
    to_zone = tz.gettz(new_zone)

    utc = datetime.strptime(time, "%H:%M")

    utc = utc.replace(tzinfo=from_zone)
    central = utc.astimezone(to_zone)
    return central

print(update_timezone("18:00", "UTC+3","UTC-5"))

Output:

1900-01-01 10:00:00-05:00

Desired output:

11:00

A:
The date is fine, I can remove that.

Better than converting to a string and then trying to munge that, just keep it as a datetime object until you need a string, and then use the strftime method to format it however you want. For example:
>>> dt.strftime('%H:%M')
10:00

Or, if you're using f-strings or str.format, you can even put that directly in the format spec for a datetime object:
>>> print(f'The time sponsored by Accurist is {dt:%H:%M}, precisely.')
The time sponsored by Accurist is 10:00, precisely.

I am not sure why the time though seems to be a range?

Actually, it's not. The default str format for displaying datetime objects is based on ISO 8601.1 For local times that know their time zone's UTC offset at the time in question, it's included as a +02:00 or -05:00 on the end.

I was expecting 24 hour format output.

That's already the default for the str output.
But, more importantly, that's what you always get when you ask strftime for %H. (If you want 12 hour, that's %I.)

1. But not with default settings for all of the options, like T as the time separator. If you want that, you have to call the isoformat method.


text:
Q: How to mock a called function using jest? I am writing tests for functions in a file. Several functions call another function which is also in that file. Here is how it looks:
function importantFunc(str) {
  //some logic
  return result;
}

function funcA() {
  //some logic
  const result = importantFunc('test A')
  //some logic
}

function funcB() {
  //some logic
  const result = importantFunc('test B')
  //some logic
}

I have already written a test for importantFunc. Problem is how can I test mock the call to importantFunc in funcA and funcB so that they will not call importantFunc directly, but use the result I provide in my mock?
Between jest.spyOn and jest.fn, I am thinking jest.fn may work. But I cannot figure out how it will tie to funcA or funcB.

A: You generally can't, unless if you're importing importantFunc from another module, in which case you mock the whole module.
What you should do is refactor your code so your units are not tightly coupled to one-another.
// in impl
function funcA(importantFunc) {
  //some logic
  const result = importantFunc('test A')
  //some logic
}

function funcB(importantFunc) {
  //some logic
  const result = importantFunc('test B')
  //some logic
}

// ...
// ...

// in test
const importantFunc = jest.fn(() => { ... });
funcB(importantFunc)


text:
Q: Basic REST API with Nodejs and Express4 I have been trying to create a quick REST API using Nodejs and Express4 as I need an API quickly to make a prototype. While I need all basic CRUD operations, I tried to run the example from the following URL: http://runnable.com/U7bnCsACcG8MGzEc/restful-api-with-node-js-express-4
The example at this address only supports GET, but I believe I could quickly adapt it to support POST, PUT and DELETE. I do not care of having the data on memory, it is even preferable.
You can click to see the code there.
However, once I have started my server and go on http://localhost:8080/players
I get "Cannot GET /players" in my browser.
Any idea? If somebody has another short/quick example of a REST API with Nodejs with in-memory persistence, I'll take it as well :)

A: If you want to create quick API with CRUD operation then try npm deployd , but there is not express. If u love to code then use express-generator

A: Please refer following code to create REST API using ExpressJS.
Server.js
var express = require("express");
var mysql   = require("mysql");
var bodyParser  = require("body-parser");
var rest = require("./REST.js");
var app  = express();

function REST(){
    var self = this;
    self.connect_to_mysql();
}

REST.prototype.connect_to_mysql = function() {
    var self = this;
    var pool      =    mysql.createPool({
        connectionLimit : 100,
        host     : 'localhost',
        user     : 'root',
        password : '',
        database : 'restful_api_demo',
        debug    :  false
    });
    pool.getConnection(function(err,connection){
        if(err) {
          self.stop(err);
        } else {
          self.configureExpress(connection);
        }
    });
}

REST.prototype.configureExpress = function(connection) {
      var self = this;
      app.use(bodyParser.urlencoded({ extended: true }));
      app.use(bodyParser.json());
      var router = express.Router();
      app.use('/api', router);
      var rest_router = new rest(router,connection);
      self.start_server();
}

REST.prototype.start_server = function() {
      app.listen(3000,function(){
          console.log("All right ! I am alive at Port 3000.");
      });
}

REST.prototype.stop = function(err) {
    console.log("ISSUE WITH MYSQL \n" + err);
    process.exit(1);
}

new REST(); // Instantiate class.

REST.js
function REST_ROUTER(router,connection) {
    var self = this;
    self.handle_routes(router,connection);
}

REST_ROUTER.prototype.handle_routes = function(router,connection) {
    router.get("/",function(req,res){
        res.json({"Message" : "Hello World !"});
    })
}

module.exports = REST_ROUTER;

Link : http://codeforgeek.com/2015/03/restful-api-node-and-express-4/


text:
Q: Domain Controllers as internal DNS servers Our company environment is growing rapidly and I'm in the process of upgrading our Domain Controllers, but before I do I wanted to do a quick sanity check to make sure I'm still doing everything the best way possible.
Focusing on my primary HQ site, I have 3 domain controllers (2 virtual, 1 physical) all running Windows Server 2008 R2. I wish to migrate to Windows Server 2012 R2. I don't believe in 'upgrading' Windows, I always prefer 'migration' to keep the servers/environments clean of upgrade artifacts.
The two virtual DCs provide all DNS services for all of my workstations and member servers. Workstations get the DNS addresses through DHCP options while all member servers have the DNS server IPs configured static.
Question:
Is it still normal to use your domain controllers as the DNS resolvers for all of your workstations and servers, or should I create new dedicated DNS servers?
Question:
Is it good practice to use the real IPs of the domain controllers on workstations and servers for DNS resolvers or should I use virtual IPs/load balancing?

A:
Is it still normal to use your domain controllers as the DNS resolvers
  for all of your workstations and servers, or should I create new
  dedicated DNS servers?

I have 2000+ clients in my company and 4 domain controllers. 2 of them are also acting as DNS Server with no issue for 4 years now.

Is it good practice to use the real IPs of the domain controllers on
  workstations and servers for DNS resolvers or should I use virtual
  IPs/load balancing?

Once again, for 2000+ clients i use real DNS resolver IP with no issues.
I provide these metrics as a kind of "reference". Depending on your number of clients, DNS load could be higher and my topology could not applies to you...But IMHO you can go safely with DC+DNS
As stated by Microsoft :

Most often, you will install DNS servers on all domain controllers

But i let you read the full article here

A: Using your DCs as DNS servers is quite reasonable.  Also, you can't really hide them since so many things require direct communication with them.
The only reason you wouldn't want to use them as your DNS servers is if the load of DNS is too high and lots of queries are for the same names, at which point you'd want to use an intermediate resolver that caches things, or if you want to do fancy things with DNS that would be better served by something like BIND.  If you need to change later, you can always change your DNS options, and if you have more than two domain controllers you can also vary the DNS servers on each of your subnets to help balance load.
The security risk of using DCs like this is pretty much zero.

A: As a datapoint, I work for a Fortune 200 in the Financial Services industry, and for about a year, served as the DNS Hostmaster for the enterprise. We used to use the built-in Microsoft DNS solution (and F5 LTM for IP anycasting the resolver address and the nameserver in the SOA), which works, but which we decided was non-optimal for our purposes.
Points in its favor

*

*Free as part of Active Directory

*Works well enough for basic use

*Automatic enrollment of DNS records for DHCP clients (if the clients were Windows clients ; Mac, Linux and SunOS, not so much)

Reasons we needed more

*

*In an effort to be permissive, it does not strictly follow the spec, allowing in incorrect or even impossible information (including CNAME at zone-apex, for which there was an unapproved proposed RFC, but much, much worse, records with whitespace in either the record-name or the response-value, which confuses the hell out of anything BIND-based)

*The mechanism to keep associated A,TXT,SRV,PTR records synchronized was not sufficient, and we spent substantial time manually reconcilling

*The integrated DHCP daemon required split-scopes for HA, meaning in a fault-condition, half the vailable pool is lost, rather than the standards-track (and used in ISC-based solutions) DHCP failover (https://kb.isc.org/article/AA-00502/0/A-Basic-Guide-to-Configuring-DHCP-Failover.html)

*There was not an out-of-the-box mechanism to easily visualize IP exhaustion/availability/density based on the PTR records

We wound up implementing a top-tier integrated DHCP+DNS+IPAM solution and haven't looked back (including having it perform dynamic zone synchronization and IP Anycast).
There is, of course, a caveat: for SRV record registration to work for Active Directory Service Discovery and for Windows Cluster Server record registration and deregistration to work. you must create an ACL that contains all the domain controllers and MS Cluster Server boxes, and allow them to perform dynamic DNS updates. To insure data integrity and sanity, for all other hosts and all other records, you should only allow them to update via the DHCP daemon or via the GUI/API (in other words, disallow dynamic DNS updates and AXFR for all non-whitelisted boxes).


text:
Q: Как найти все слова, которые имеют только одну Заглавную букву в строке и не имеют числа? Нужна помощь с решением регулярных выражений.
Задача проста, нужно найти все слова, которые имеют только одну Заглавную букву в строке и не имеют числа.
Я пытался что-то вроде такого сделать, но безуспешно:
import re
pattern = r"\b\w[а-яА-ЯёЁ]\w+(?![0-9])\b"
result = re.findall(pattern, 'Яблоко яБлоко ябЛоко яблОко яблоКо яблокО яблоко7 яблоко')
print(result)

Я очень плохо понимаю как устроены регулярные выражения. Помогите решить задачу и объясните мне потом, пожалуйста, почему именно так нужно сделать.

A: Если вы хотите использовать регулярные выражения, установите библиотеку PyPi regex с помощью pip install regex используйте
import regex
pattern = r"\b\p{Ll}*\p{Lu}\p{Ll}*\b"
text = 'Яблоко яБлоко ябЛоко яблОко яблоКо яблокО яблоко7 яблоко'
result = regex.findall(pattern, text)
print(result)
# => ['Яблоко', 'яБлоко', 'ябЛоко', 'яблОко', 'яблоКо', 'яблокО']

См. пример выполнения кода.
Если регулярные выражения использовать необязательно, вы можете использовать
import re, sys
uc_letters = [chr(i) for i in range(sys.maxunicode) if chr(i).isupper()]
text = 'Яблоко яБлоко ябЛоко яблОко яблоКо яблокО яблоко7 яблоко'
print( [slovo for slovo in text.split() if all(c.isalpha() for c in slovo) and len([c for c in slovo if c in uc_letters]) == 1 ] )
# => ['Яблоко', 'яБлоко', 'ябЛоко', 'яблОко', 'яблоКо', 'яблокО']

См. пример кода.
Подробности:

*

*uc_letters - список всех заглавных букв Юникода

*[slovo for slovo in text.split()... - разбивает строку на слова по пробельным символам, а затем оставляет только те, которые

*if all(c.isalpha() for c in slovo) and... состоят целиком из букв и

*len([c for c in slovo if c in uc_letters]) == 1 ] в которых имеется только одна заглавная буква.


text:
Q: Why aren't Java.util.concurrent.TimeUnit types greater than SECONDS available in Android? I miss MINUTES, HOURS, DAYS, which exist in documentaion since API level 1 (I use 7th or 2.1 version for the application).
I have read this question, where this miss was also pointed out (though, it wasn't in the question itself), but as solution making own calculations was only proposed.
I am not lazy, but I send some data to server (Java project), where TimeUnit.MINUTES or TimeUnit.HOURS are actively used. Just want to avoid mistakes.
Will be grateful for any help.

A: If you open the javadoc for TimeUnit on java 5 and java 6 side by side you will see that these were added in java 6. Android so far only implements java 5.


text:
Q: Display name of near by places of current location using google map api I am making a web application in which user can search parking spaces.when user clicks on a particular parking space its map is appeared. I also want to find the places nearby that location and display their address/name on my web page.
How can i do this using jquery in asp.net.


text:
Q: Problemas com os ifs no react native Boa tarde! Tenho um código em javascript de uma aplicação em react, mas por algum motivo a minha IDE está acusando um erro numa linha em que se encontra um else de um if, mas não sei como resolver-lo!
O erro encontra-se em laranja.
Provavelmente o erro seja muito estúpido, mas sou novo em javascript!
<View style={styles.form}>
    { showBox ? colorBox == "warm" ? <View style={styles.boxWarm}><Text style={styles.boxWarmText}>{boxText}</Text></View> : colorBox == "error" ?
        <View style={styles.boxError}><Text style={styles.boxWarmText}>{boxText}</Text></View> : <View style={styles.boxOk}><Text style={styles.boxWarmText}>{boxText}</Text></View> : null }
    { showContent ?
        <Text style={styles.label}>INSIRA A NOVA PASSWORD:</Text>
        <TextInput
            style={styles.input}
            textContentType="password"
            placeholder="Introduza a nova password"
            secureTextEntry={true}
            placeholderTextColor="#999"
            value={newPass}
            ref={(input) => this.newpass = input}
            onChangeText={pass => hideInfoDuringTyping(pass, "newpass") }
            onSubmitEditing={() => this.renewpass.focus()}
        />
        <Text style={styles.label}>INSIRA A NOVA PASSWORD:</Text>
        <TextInput
            style={styles.input}
            textContentType="password"
            placeholder="Introduza novamente a nova password"
            secureTextEntry={true}
            placeholderTextColor="#999"
            value={renewpass}
            ref={(input) => this.renewpass = input}
            onChangeText={pass => hideInfoDuringTyping(pass, "renewpass") }
            onSubmitEditing={handleRecover}
        />

: null }

        { showInfo ?
            <Text style={colorInfo == "warm" ? styles.infoWarm : colorInfo == "error" ? styles.infoError : styles.infoOk }>{infoText}</Text> : null }
        <TouchableHighlight onPress={handleRecover} style={styles.buttonMain}><Text style={styles.buttonTextMain}>Alterar a password</Text></TouchableHighlight>
        <TouchableHighlight onPress={startSession} style={styles.buttonSecundary}><Text style={styles.buttonTextSecundary}>{btnTxt}</Text></TouchableHighlight>
</View>

A: Pois no javascript react não é aceito mais de uma tag como retorno.
ou seja:
isso aqui pode ser feito:
{ showContent ?
<View>
 <Text style={styles.label}>INSIRA A NOVA PASSWORD:</Text>
 <TextInput
    style={styles.input}
    textContentType="password"
    placeholder="Introduza a nova password"
    secureTextEntry={true}
    placeholderTextColor="#999"
    value={newPass}
    ref={(input) => this.newpass = input}
    onChangeText={pass => hideInfoDuringTyping(pass, "newpass") }
    onSubmitEditing={() => this.renewpass.focus()}
 />
 ...
</View>
: null }

pois o retorno da condição é apenas uma tag, no caso View, o exemplo abaixo mostra um erro ao retornar duas tags ao inves de uma encapsulando elas.
{ showContent && <Text>Oi</Text><Text>Tomas</Text> : null }

uma dica, você pode usar && para retornar uma condição caso verdadeiro, eliminando o : null do seu código ex:
{ showContent &&
  <View>
   <Text style={styles.label}>INSIRA A NOVA PASSWORD:</Text>
    <TextInput
       style={styles.input}
       textContentType="password"
       placeholder="Introduza a nova password"
       secureTextEntry={true}
       placeholderTextColor="#999"
       value={newPass}
       ref={(input) => this.newpass = input}
       onChangeText={pass => hideInfoDuringTyping(pass, "newpass") }
       onSubmitEditing={() => this.renewpass.focus()}
    />
    ...
  </View>
}


text:
Q: Trouble with formatting input as JSON format with java Hi all I have a trouble with my java program. Essentially I'm writing a program that asks the user for a book's title, author, price, and isbn. Then it takes the input that stores it to my Book class that stores the input and has a toString method that prints out the contents similar to JSON formatting.
Then my books class uses an Array list to store the Book objects and has a toString method that prints out the entire set of books in JSON format. Problem is it doesn't format it properly. The problem lies within my if and else statement in my code. Heres my code:

import java.util.ArrayList;
public class Books
{
  private ArrayList<Book> books;

  public Books()
  {
    books = new ArrayList<Book>();
  }
  public void add(Book bk)
  {
    books.add(bk);
  }
  public String toString()
  {
    String temp = "{\n ";
    temp = temp + "  \"books:\": [\n";
    int bookCount = 0;
    for (Book bk : books) {
      temp += bk.toString();
      bookCount++;//add +1 to bookcount
      if (bookCount < books.size()-1) {
        temp += ",\n";
      }
      else {
        temp += "\n  ]\n}\n";
      }
    }
    return temp;
  }
}

When I run my program it looks like this:
Results
My goal is to have it look like this:
WantedResults
So after parsing the first book correctly by adding the ",\n"; . But each book being parsed after it adds the "\n  ]\n}\n"; which I only want to be added to the last one. :( Please help.
Thanks in advance

A: The problem is that you increase the bookCount value before the checking condition.
If you are not using enhanced for loop, the code will look like this
for (int bookCount = 0; bookCount < books.size()-1; bookCount++)  {
    Book book = books.get(i);
    //  print book
    //  check Condition
}

bookCount should be added after checking condition

A: Don't do that, use a proper JSON library to properly parse or create the JSON data structures.
Here is a tutorial to get you started.
http://java.sg/parsing-a-json-string-into-an-object-with-gson-easily/

A: Use Jackson:
...
ObjectMapper mapper = new ObjectMapper ();
mapper.writeValue (new java.io.Writer ().write (jsonifiedStr), books);
System.out.println (jsonifiedStr);
...


text:
Q: Maven cannot find JRuby mojo descriptors I followed the instructions to the letter in this blog post by Sonatype on writing a Maven plugin in Ruby.
When I try running mvn install (Maven 3.0.4), the build is successful, but maven-plugin-plugin cannot find any mojo descriptors:
[INFO] ------------------------------------------------------------------------
[INFO] Building Example Ruby Mojo - firstruby-maven-plugin 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[WARNING] The POM for org.jruby:jruby:jar:0.9.9 is invalid, transitive dependencies (if any) will not be available, enable debug logging for more details
[INFO]
[INFO] --- maven-plugin-plugin:2.4:descriptor (default-descriptor) @ firstruby-maven-plugin ---
[INFO] Using 3 extractors.
[INFO] Applying extractor for language: java
[INFO] Extractor for language: java found 0 mojo descriptors.
[INFO] Applying extractor for language: jruby
[INFO] Extractor for language: jruby found 0 mojo descriptors.
[INFO] Applying extractor for language: bsh
[INFO] Extractor for language: bsh found 0 mojo descriptors.

If I try bumping maven-plugin-plugin version to anything higher than 2.4, the build fails with this error message:
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-plugin-plugin:2.5:descriptor (default-descriptor) on project firstruby-maven-plugin: The API of the mojo scanner is not compatible with this plugin version. Please check the plugin dependencies configured in the POM and ensure the versions match. org.apache.maven.tools.plugin.scanner.MojoScanner.populatePluginDescriptor(Lorg/apache/maven/tools/plugin/PluginToolsRequest;)V -> [Help 1]

Here's the output of tree to show that the directory structure is OK:
firstruby-maven-plugin
├── pom.xml
└── src
    └── main
        └── scripts
            └── echo.rb

3 directories, 2 files

Any idea why it's not working?

A: The Codehaus jruby-maven-plugin seems to have been abandoned 5 years ago. If you're using Maven3, you can try using Maven2 but I'd look at https://github.com/torquebox/jruby-maven-plugins


text:
Q: Dependency added to pom can not be resolved I am trying to add a dependency to my pom.xml and facing an issue: IntelliJ error

Cannot resolve jfugue:jfugue:5.0.9

The dependency I like to add is this one below from https://mvnrepository.com/artifact/jfugue/jfugue/5.0.9
<!-- https://mvnrepository.com/artifact/jfugue/jfugue -->
<dependency>
    <groupId>jfugue</groupId>
    <artifactId>jfugue</artifactId>
    <version>5.0.9</version>
</dependency>

I have no problems adding other dependencies just by adding the xml-snippet from maven into my pom and refresh or reload all maven projects. For example I have this dependency in the same pom which is working fine:
<!-- https://mvnrepository.com/artifact/org.jsoup/jsoup -->
<dependency>
    <groupId>org.jsoup</groupId>
    <artifactId>jsoup</artifactId>
    <version>1.14.3</version>
</dependency>

However, there is a note under the snippet which one can copy-paste, https://mvnrepository.com/artifact/jfugue/jfugue/5.0.9

Note: this artifact is located at SingGroup repository (https://maven.sing-group.org/repository/maven/)

What do I need to add to the pom so that I can use that dependency in my Project and get rid of the error?

Cannot resolve jfugue:jfugue:5.0.9

Thanks in advance.

A: You can add the repository to your settings.xml Maven Guide
<profiles>
    <profile>
        <id>multi-repo</id>
        <repositories>
            <repository>
                <id>MavenCentral</id>
                <url>https://repo.maven.apache.org/maven2/</url>
            </repository>
            <repository>
                <id>MavenSing</id>
                <url>https://maven.sing-group.org/repository/maven//</url>
            </repository>
        </repositories>
     </profile>
 </profiles>

A: This Lib is no longer on the Maven repo. I get same result when adding the dependency to my project's POM file. You can get the JAR file from this URL and then include it into your project's class path:
http://www.jfugue.org/download.html


text:
Q: Method to get down and up objective valuses at each node in CPLEX concert C++? I would like to compute strong branching with getStrongBranch function in CPLEX concert with C++.
getStrongBranch(IloNumArray downobj, IloNumArray upobj, const IloNumVarArray var, IloInt itmax)

The method like getObjValue reports the value of objective. Is there any method to get the value of downobj and upobj for a variable which is selected for branching?

A: You can use the IloCplex::ControlCallbackI's methods getUpPseudoCost and getDownPseudoCost. If you also set the variable selection to full strong branching this will be close to strong branching score.
Other than that there is no function to get more detailed strong branching information inside a callback.


text:
Q: SAS proc tabulate questions My dataset looks like this:
 ID Var1    Var2    Var3
 A    1      0       1
 B    0      0       1
 B    1      1       0
 A    0      0       0
 A    1      1       1

My expected output will be:
    ID  Var1    Var2    Var3
    A   2        1       3
    B   1        1       1

Can someone help with this?

A: I've not access to SAS right now but try the following:-
proc tabulate data = in;
  class id;
  var var:;
  table id, sum=''*(var1 var2 var3);
run;


text:
Q: How to make on div on top of another with table-cell? I'm trying to make two divs to be one on top of another, like this:

The fiddle:

.table {
  display:table;
}
.div1 {
  display:table-cell;
  vertical-align:middle;
}
.div2 {
  display:table-cell;
  vertical-align:bottom;
}

    Top

    Bottom

A: Put a wrapper element with display: table-row; in each table-cell element you want to isolate. This will stack the cells in different rows, one on top of the other.
And don't use tables for your layout ... here's why: Why not use tables for layout in HTML?

A: when I did the fiddle.... I came up with this (no css)

            Socrates (this should be on top of his head)

A: Try this:
Html:

        Socrates (this should be on top of his head)

CSS:
.table {
    display:table;
}
.align-middle {
    display:table-cell;
    vertical-align:left;
}


text:
Q: Speed of convergence for Monte Carlo integration I am following this Wikipedia page on naive Monte Carlo method. Here is my slightly modified "proof"/reasoning for the $\mathcal{O} (N^{-1/2})$ speed of convergence of the method. I would like to have comments on whether I have understood the reasoning correctly.
The method:
Let $\Omega \subset \mathbb{R}^n $ and let $\mu$ denote the $n$-dimensional Lebesgue measure. Let $x_1, x_2, \dots, x_N$ be a sample from the uniform distribution of $\Omega$. Thus, the probability density function is
$$ \rho(x)=\begin{cases}
1/\mu\left(\Omega\right){,}&\mathrm{in}\ \Omega{,}\\
0{,}&\mathrm{otherwise.}
\end{cases}$$
Then the method
$$ \int_\Omega f \mathrm{d}\mu \simeq \frac{\sum_{k=1}^N f(x_i)}{N} \mu(\Omega)$$
has $\mathcal{O} (N^{-1/2}) $ speed of convergence.
Proof:
Let $X_1, X_2, \dots, X_N$ be i.i.d. random variables. The distribution is the uniform distribution on $\Omega$. Thus, $f(X_1), f(X_2), \dots, f(X_N)$ are i.i.d. random variables as well. We denote the variance of $f(X_1), f(X_2), \dots, f(X_N)$ by $\sigma^2$.
The speed of convergence, i.e., the standard deviation of the method is
$$
\sqrt{\mathrm{Var}\left(\frac{\sum_{k=1}^Nf\left({X}_k\right)}{N}\mu\left(\Omega\right)\right)} = \sqrt{\frac{\mu \left(\Omega \right)^2}{N^2}\mathrm{Var}\left(\sum _{k=1}^Nf\left({X}_k\right)\right)} \\
     = \sqrt{\frac{\mu \left(\Omega \right)^2}{N^2}\sum _{k=1}^N\mathrm{Var}\left(f\left({X}_k\right)\right)} \\
     = \sqrt{\frac{\mu\left(\Omega\right)^2}{N^2}N\sigma^2} =\frac{\mu \left(\Omega \right)\sigma }{\sqrt{N}}.
$$
Here $\mu(\Omega) \sigma $ is constant. Thus, the standard deviation is $\mathcal{O} (N^{-1/2})$.
By saying that the method converges, we mean that for large $N$, the standard deviation is close to zero. That is, for large enough $N$, "on average" it holds that
$$  \left(\frac{\sum_{k=1}^N f(X_i)}{N} \mu(\Omega)-\int_\Omega f \mathrm{d}\mu \right)^2 \approx 0,$$
since
$$ \mathbb{E} \left(f(X_i)\right)=\frac{1}{\mu(\Omega)} \int_{\Omega} f \mathrm{d}\mu. $$
However, that does not guarantee that the result or even the average of results of the method are close to 0. By law of large numbers, the average is close to zero with a high probability.


text:
Q: Radio Button As image is not working properly in Internet Explorer Edge In IE Edge  radio button get checked/unchecked when in click on label text(Male/female) but not when I click on image adjacent to male/female. Where as in other browser radio button get checked/unchecked when  i click on image as well as text(Male/Female).
Html:

Which gender do you identify with?

<input type="radio" name="gender"  id="male" class="input-hidden" ng-model="genderSelect" ng-value = "'male'" ng-change = "genderSelection(genderSelect)" required/>

  Male

<input type="radio" name="gender" id="female" class="input-hidden" ng-model="genderSelect" ng-value = "'female'" ng-change = "genderSelection(genderSelect)" required/>
 Female

CSS:
.input-hidden{
 visibility: hidden;
 position: absolute;
 }

Js:
$scope.genderSelection = function(gender){

  if(gender == 'male'){
  $scope.imgPathMale = "assets/images/form_radio_selected.png";
  $scope.imgPathFemale = "assets/images/form_radio_unselected.png";
  }
  else{
  $scope.imgPathFemale = "assets/images/form_radio_selected.png";
  $scope.imgPathMale = "assets/images/form_radio_unselected.png";
  }
 }

A: label{
   display:inline-block;
}
label img{
 pointer-events: none;
 -moz-user-select: -moz-none; // to remove blue color highlight in which we
   //get on clicking image in firefox.
}


text:
Q: Issue returning an abstract type with a higher rank trait bound I'm trying to write a generic trait for sending messages between processes. The simplified version of it looks like this:
trait Sender<T> {
    fn send_msg(&mut self, to: u64, body: T) -> Result<()>;
}

I want to be able to send messages that contain references, so as to avoid copying data:
#[derive(Serialize)]
enum MsgBody<'a> {
    Success,
    Fail(Error),
    Write { offset: u64, buf: &'a [u8] },
}

However I've run into an issue where the type parameter T can only refer to a single lifetime, preventing references of any lifetime from being used. To illustrate this consider this dummy implementation of Sender<T>:
struct SenderImpl<T>(PhantomData<T>);

impl<T: Serialize> Sender<T> for SenderImpl<T> {
    fn send_msg(&mut self, to: u64, body: T) -> Result<()> {
        Ok(())
    }
}

Now if I try to return a sender that will work for any lifetime parameter
fn ref_sender() -> impl for<'a> Sender<MsgBody<'a>> {
    SenderImpl(PhantomData)
}

then I get a compilation error because the type parameter T is not generic over all possible lifetimes:
error: implementation of `Sender` is not general enough
  --> src/lib.rs:29:5
   |
29 |     SenderImpl(PhantomData)
   |     ^^^^^^^^^^^^^^^^^^^^^^^ implementation of `Sender` is not general enough
   |
   = note: `SenderImpl<MsgBody<'2>>` must implement `Sender<MsgBody<'1>>`, for any lifetime `'1`...
   = note: ...but it actually implements `Sender<MsgBody<'2>>`, for some specific lifetime `'2`

The error makes sense but I'm not sure how to express what I want. What I'd like to say is this
fn ref_sender() -> impl for<'a> Sender<MsgBody<'a>> {
    SenderImpl(PhantomData::<for<'a> MsgBody<'a>>)
}

but of course for<'a> MsgBody<'a> is not actually a type.
I can work-around this by using MsgBody in the Sender trait rather than making it generic (you can see that here). I don't like this solution though as it sacrifices flexibility.
Is there a way to get the generic Sender<T> to work with types that have a lifetime parameter?
Edit: Here's the code used in this question:
https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=0aac9134639e9593698bfe9da7722d9f

A: Instead of making the trait generic, move the generic type parameter to send_msg:
trait Sender {
    fn send_msg<T: Serialize>(&mut self, to: u64, body: T) -> Result<()>;
}

Then every call to send_msg can use a different lifetime parameter. The full solution is here.

A: As you've noted, &T needs a lifetime to be a complete type and for<'a> &'a T doesn't exist. The concrete problem is that SenderImpl<T> must have a complete type T and only implements Sender with that type.
You can workaround this by avoiding references in SenderImpl<T> (by making T = [u8]) and allow it to implement Sender<&T> for any lifetime:
struct SenderImpl<T: ?Sized>(PhantomData<T>);

impl<'a, T: Serialize + ?Sized> Sender<&'a T> for SenderImpl<T> {
    fn send_msg(&mut self, to: u64, body: &'a T) -> Result<()> {
        Ok(())
    }
}

Edit:

This approach doesn't seem to work in the case where T has it's own lifetime parameter.

You could also make it generic over any specific type with lifetimes, just SenderImpl won't have a specific type associated with it beyond what the trait implementation implies:
struct SenderImpl;

impl<'a> Sender<MsgBody<'a>> for SenderImpl {
    fn send_msg(&mut self, to: u64, body: MsgBody<'a>) -> Result<()> {
        Ok(())
    }
}

fn ref_sender() -> impl for<'a> Sender<MsgBody<'a>> {
    SenderImpl
}

Or, similarly to the self-answer, you can implement Sender<T> for any type. But like the above, SenderImpl obviously won't be specific to any in particular:
struct SenderImpl;

impl<T: Serialize> Sender<T> for SenderImpl {
    fn send_msg(&mut self, to: u64, body: T) -> Result<()> {
        Ok(())
    }
}

fn ref_sender() -> impl for<'a> Sender<MsgBody<'a>> {
    SenderImpl
}