text:
Q: Simulating Poisson Waiting Times I need to simulate Poisson wait times.  I've found many examples of simulating the number of arrivals, but I need to simulate the wait time for one arrival, given an average wait time.
I keep finding code like this:
public int getPoisson(double lambda)
{
    double L = Math.exp(-lambda);
    double p = 1.0;
    int k = 0;

    do
    {
        k++;
        p *= rand.nextDouble();
        p *= Math.random();
    } while (p > L);

    return k - 1;
}

but that is for number of arrivals, not arrival times.
Efficieny is preferred to accuracy, more because of power consumption than time.  The language I am working in is Java, and it would be best if the algorithm only used methods available in the Random class, but this is not required.

A: Time between arrivals is an exponential distribution, and you can generate a random variable X~exp(lambda) with the formula:
-ln(U)/lambda` (where U~Uniform[0,1]).

More info on generating exponential variable.
Note that time between arrival also matches time until first arrival, because exponential distribution is memoryless.

A: If you want to simulate earthquakes, or lightning or critters appearing on a screen, the usual method is to assume a Poisson Distribution with an average arrival rate λ.
The easier thing to do is to simulate inter-arrivals:
With a Poisson distribution, the arrivals get more likely as time passes. It corresponds to the cumulative distribution for that probability density function. The expected value of a Poisson-distributed random variable is equal to λ and so is its variance.
The simplest way is to 'sample' the cumulative distribution which has an exponential form  (e)^-λt  which gives t = -ln(U)/λ. You choose a uniform random number U and plug in the formula to get the time that should pass before the next event.
Unfortunately, because U usually belongs to [0,1[ that could cause issues with the log, so it's easier to avoid it by using t= -ln(1-U)/λ.
Sample code can be found at the link below.
https://stackoverflow.com/a/5615564/1650437


text:
Q: R: How do you initialise datatables FixedColumns javascript in Shiny? I am trying to build a shiny app that uses the datatable FixedColumns plugin:
https://datatables.net/extensions/fixedcolumns/
The datasest I am using will have around 100 columns and I want to fix the first five columns and allow the user to scroll through the rest. From the examples it looks like I'd need to use this javascript:
https://datatables.net/release-datatables/extensions/FixedColumns/examples/two_columns.html
$(document).ready(function() {
    var table = $('#example').DataTable( {
        scrollY:        "300px",
        scrollX:        true,
        scrollCollapse: true,
        paging:         false
    } );
    new $.fn.dataTable.FixedColumns( table, {
        leftColumns: 2
    } );
} );

I don't know javascript but in the past I have been able to use I() to insert javascript options. This time though it looks like I need to do something else. I've tried the code below and get the message: "ERROR: 'options' must be a named list'.
library(shiny)
library(ggplot2)
data(diamonds)
hw <- diamonds

runApp(
  list(ui=(
    fluidPage(
      tabsetPanel(
        id = 'dataset',
        tabPanel('hw', dataTableOutput('mytable1'))
      ))),

    server = (function(input, output, session) {
      output$mytable1 <- renderDataTable(
        head(hw, 50),
        options = list(scrollY = '300px',
                       scrollX = TRUE,
                       scrollCollapse = TRUE,
                       paging = FALSE,

                       I("new $.fn.dataTable.FixedColumns( table, {
                        leftColumns: 5
                        } );")
                       ))

    })

  ))

A: In case anyone comes across this question more recently, you can now use the FixedColumns extension directly without any javascript:
https://rstudio.github.io/DT/extensions.html
m = as.data.frame(round(matrix(rnorm(100), 5), 5))
datatable(
  m, extensions = 'FixedColumns',
  options = list(
    dom = 't',
    scrollX = TRUE,
    fixedColumns = TRUE
  )
)

A: list(tags$head(tags$script('type = "text/javascript"', '
        $(document).ready( function () {
            var table = $("#example").DataTable( {
                "scrollY": "300px",
                "scrollX": "100%",
                "scrollCollapse": true,
                "paging": false
            } );
            new $.fn.dataTable.FixedColumns( table );
        } );
')))

redpajama_set_name: RedPajamaStackExchange


text:
Q: AWS - Elastic BeanTalk: [error] 'php' not found or unable to stat I have a simple website deployed on Elastic BeanTalk ( platform: PHP 5.6 ).
public
   |about.html
   |index.html
   |style.css
   |+ include
         |subscribe-email.php
         |+ phpmailer

When I checked the log, I received many errors related to '.php' not found or unable to stat. I don't know from where these php files were generated.
[Thu Jun 21 06:18:52.967190 2018] [:error] [pid 12523] [client xxx] script '/var/www/html/xxxx/public/wp-login.php' not found or unable to stat
[Thu Jun 21 06:25:46.354172 2018] [:error] [pid 12742] [client xxx] script '/var/www/html/xxxx/public/wp-login.php' not found or unable to stat
[Thu Jun 21 06:44:44.392342 2018] [:error] [pid 12963] [client xxx] script '/var/www/html/xxxx/public/wp-login.php' not found or unable to stat
[Thu Jun 21 07:18:12.899793 2018] [:error] [pid 13726] [client xxx] script '/var/www/html/xxxx/public/index.php' not found or unable to stat
[Thu Jun 21 07:18:24.145541 2018] [:error] [pid 13531] [client xxx] script '/var/www/html/xxxx/public/wuwu11.php' not found or unable to stat
[Thu Jun 21 07:18:24.925862 2018] [:error] [pid 13418] [client xxx] script '/var/www/html/xxxx/public/xw.php' not found or unable to stat
[Thu Jun 21 07:18:25.689064 2018] [:error] [pid 13418] [client xxx] script '/var/www/html/xxxx/public/xx.php' not found or unable to stat
[Thu Jun 21 07:18:26.489205 2018] [:error] [pid 13418] [client xxx] script '/var/www/html/xxxx/public/s.php' not found or unable to stat
[Thu Jun 21 07:18:27.282847 2018] [:error] [pid 13418] [client xxx] script '/var/www/html/xxxx/public/w.php' not found or unable to stat
[Thu Jun 21 07:18:28.081399 2018] [:error] [pid 13418] [client xxx] script '/var/www/html/xxxx/public/sheep.php' not found or unable

Any suggestion is appreciated.

A: It is not a solution but I had the same issue.
I'm posting it as an answer to be able to upload an image.
I found something very similar. Also PHP 5.6.
It was new droplet, recently updated. Ubuntu 16, I added a repo to be able to install PHP 5.6 instead of PHP 7 which is the default.

sudo add-apt-repository ppa:ondrej/php

Where does it comes from?


text:
Q: How can I find a redirect to a custom protocol I am trying to launch Zoom using a crontab on my X11 based Linux system. When clicking Join Meeting Firefox gives me a redirect notice, but doesn't actually give me the full URI, is there any way I can find the URI being called?
Zoom uses the zoommtg:// custom protocol, and I've gotten some functionality working, but I would really prefer a solution that could be applied to any page with obfuscated redirects.
Ive already tried developer tools but the code is obfuscated. I intend to use xdg-open to launch my meetings when I find the URI

A: The page itself logs the URL to the "Console" tab of Chrome's Developer Tools:

Launched external handler for 'zoommtg://zoom.us/join?action=join&confno=123456789&zc=64&confid=dXRpZD[...]mMTZl&browser=chrome'.

You can of course make a custom xdg-open handler (or even an xdg-open wrapper, or a 'zoom' substitute script) that'll log the opened URI somewhere, or use one of the available system tracing mechanisms to log all commands being executed together with their parameters.

A: You can get the URI that is being called with the following regex:
Pattern: ^https://(.*)\.zoom.us/j/(\d+)\?pwd=(.*)$
Replace into: zoommtg://zoom.us/join?confno=$2&pwd=$3
For example:
https://your-organization.zoom.us/j/123456789?pwd=asdfasdfasdfasdf
becomes
zoommtg://zoom.us/join?confno=123456789&pwd=asdfasdfasdf


text:
Q: How do I insert multiple conditional comments using Jade? In Jade, How can I insert multiple conditional comments like the one below?
<!-- Foundation 3 for IE 8 and earlier -->
<!--[if lt IE 9]>
    <link rel="stylesheet" href="/css/foundation3/normalize.css">
    <link rel="stylesheet" href="/css/foundation3/foundation.css">
    <link rel="stylesheet" href="/css/foundation3/app.css">
<![endif]-->
<!-- Foundation 4 for IE 9 and earlier -->
<!--[if gt IE 8]><!-->
    <link rel="stylesheet" href="/css/foundation4/normalize.css">
    <link rel="stylesheet" href="/css/foundation4/foundation.css">
<!--<![endif]-->

So far, I tried the following, but it does not create the extra <!--> and <!--<![endif]-->.
//if lt IE 9
    link(rel="stylesheet",href="/css/foundation3/normalize.css")
    link(rel="stylesheet",href="/css/foundation3/foundation.css")
    link(rel="stylesheet",href="/css/foundation3/app.css")
//if gt IE 8
    link(rel="stylesheet",href="/css/foundation4/normalize.css")
    link(rel="stylesheet",href="/css/foundation4/foundation.css")

This will simply wrap each conditional comment block in <!--[if le IE X]> ... <![endif]>. I know I can do this, but is there anything better?

A: As the question was asked back in November 2013, I believe you were asking about the old method of generating IE conditional comments by Jade.
I will answer your question giving you the new approach which was introduced in Jade version 1.0.0 (released on 22 December 2013) as you probably use the new Jade version by now.
Note that the old approach (having IE conditional comments generated by Jade comments e.g. //if IE 8) is no longer supported in Jade 1.0.0 and above and there is no intention to put it back.
The new approach is to use well formatted IE conditional comments. So in order to generate above IE conditional comments, Jade template will have to be as follows:
<!--[if lt IE 9]>
link(rel="stylesheet",href="/css/foundation3/normalize.css")
link(rel="stylesheet",href="/css/foundation3/foundation.css")
link(rel="stylesheet",href="/css/foundation3/app.css")
<![endif]-->
<!--[if gt IE 8]><!-->
link(rel="stylesheet",href="/css/foundation4/normalize.css")
link(rel="stylesheet",href="/css/foundation4/foundation.css")
<!--<![endif]-->

The output HTML will be as follows:
<!--[if lt IE 9]>
<link rel="stylesheet" href="/css/foundation3/normalize.css">
<link rel="stylesheet" href="/css/foundation3/foundation.css">
<link rel="stylesheet" href="/css/foundation3/app.css">
<![endif]-->
<!--[if gt IE 8]><!-->
<link rel="stylesheet" href="/css/foundation4/normalize.css">
<link rel="stylesheet" href="/css/foundation4/foundation.css">
<!--<![endif]-->

Note that with Jade version 1.0.0 and above it is safe to use HTML comments as Jade will ignore any line beginning with < character.
You can also visit this post on IE Conditional Comments in Jade which talks about difference between Jade version 0.35.0 and 1.0.0. It also shows alternative approach of using Jade mixins mechanism for conditional formatting.
I hope that will help.


text:
Q: Getting ip address from a socket fd (not duplicate) I am attaching my process (with root privileges) to a browser process to intercepts its system calls using ptrace. To decode the parameters of the connect() system call i got the sockfd. But i have been trying from days to get the ip address of the other end of that socket but with no success.
i came accross these 2 questions while looking around
1)Get IP address from socket descriptor?
2)Getting IP address, port and connection type from a socket fd
I followed the suggestion of the 1st question, but somehow it was giving error. something error: 'struct sockaddr_in' has no member named 'sa_data'. I digged deeper into the internet and got another hint, which i used to write this code
temp = getpeername(regs.rdi, (struct sockaddr *)&ip_addr_struct, &ip_addr_structlen);
struct sockaddr_in *s = (struct sockaddr_in *)&ip_addr_struct;
int port = ntohs(s->sin_port);
inet_ntop(AF_INET, &s->sin_addr, ip_addr, 1024);
printf("%d-%s\n", port, ip_addr);

here regs.rdi is the sockfd. But even with this code everytime i get 0-0.0.0.0
 as output. please help anyone. Is there any other way to get the ip addrres or am i doing something wrong?

A: If your requirement is to get the IP address of the connecting client, use this :)
struct sockaddr_in their_addr;

if ((*cli_fd = accept(listener, (struct sockaddr *)&their_addr,&sin_size)) == -1)
{
    close (*cli_fd);
    return -1;
}

This is the client ip address ==> inet_ntoa(their_addr.sin_addr)


text:
Q: Appending individual characters from string onto a char pointer I'm writing a parser in C, and I've got some code that looks like this:
char *consume_while(parser *self, int(*test)(char)) {
    char *result;
    while (eof(self) && (*test)(next_char(self))) {
         // append the return value from the function consumed_char(self)
         // onto the "result" string defined above.
    }
    return result;
}

But I'm kinda new to the whole string manipulation aspect of C, so how would I append the character returned from the function consumed_char(self) to the result char pointer? I've seen people using the strcat function, but that wont work as it takes two constant char pointers, but I'm dealing with a char* and a char. In java it would be something like this:
result += consumed_char(self);

What's the equivalent in C?
Thanks :)

A: In C, strings do not exist as a type, they are just char arrays with a null-terminating character. This means, assuming your buffers are big enough and filled with zeroes, it can be as simple as:
result[(strlen(result)] = consumed_char(self);

if not, your best bet is to use strcat and change your consumed_self function to return a char *.
That being said, writing a parser without basic understanding of C-style strings, is, to say the least, quite ambitious.


text:
Q: Get base address of share library using GDB How can I get the base address of share library using GDB ?
I couldn't find any easy way.

A: You can use info sharedlibrary:
$ gdb -ex 'b main' -ex r --args bash --help
(gdb) pipe info sharedlibrary | grep libtinfo
0x00007ffff7f8e6a0  0x00007ffff7f9c17c  Yes (*)     /lib/x86_64-linux-gnu/libtinfo.so.6

Note that load address will be different on each invocation due to ASLR.


text:
Q: How to flush right margin contents on even pages in two sided document? In report class with twoside option, how to flushright the marginpar contents on even pages?
The image below was produced manually inserting \hfill. I'd like to automatize it.

MWE
\documentclass[10pt,twoside]{report}
\usepackage{lipsum}
\usepackage{showframe}

\begin{document}
\lipsum*[2]\marginpar{Lorem\dots}
\clearpage
\lipsum*[3]\marginpar{Lorem\dots}
%\lipsum*[3]\marginpar{\hfill Lorem\dots} % <-- desired output
\end{document}

A: Is using marginnote package an option ?
\documentclass[10pt,twoside]{report}
\usepackage{lipsum,marginnote}
\usepackage{showframe}

\begin{document}
\lipsum*[2]\marginnote{Lorem\dots}
\clearpage
\lipsum*[3]\marginnote{Lorem\dots}
%\lipsum*[3]\marginpar{\hfill Lorem\dots} % <-- desired output
\end{document}

A: \documentclass[10pt,twoside]{report}
\usepackage{lipsum}
\usepackage{showframe}
\usepackage{changepage}

\newcommand{\mymarginpar}[1]{
  \checkoddpage\ifoddpage\marginpar{#1\dots\hfill}\else\marginpar{\hfill\dots #1}\fi
}

\begin{document}
\lipsum*[2]\mymarginpar{Lorem}
\clearpage
\lipsum*[3]\mymarginpar{Lorem}
\end{document}

Edit:
The command mymarginpar just checks if the page is odd or not. If it is odd, the command insert the text and then \hfill, if it is not odd, then \hfill is insert before the text. The command \dots may or may not be part of the command.
Results are presented below.


text:
Q: Fetching a single sheet from a Google Spreadsheet as bytes in Ruby I'm trying to retrieve a single sheet from a google spreadsheet in excel format, I have all the access setup correctly and can run different google sheet v4 api functions on it.
I wanted to use the Google::Apis::SheetsV4::SheetsService::copy_spreadsheet function to copy a single sheet as mentioned in the Ruby example here - https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.sheets/copyTo
This is my code -
service = Google::Apis::SheetsV4::SheetsService.new
service.client_options.application_name = APPLICATION_NAME
service.authorization = authorize

spreadsheet_id = "<passing my spreadsheet id here>"
gid = "<setting this as my sheet id from the spreadsheet>"
request = Google::Apis::SheetsV4::CopySheetToAnotherSpreadsheetRequest.new(
        destination_spreadsheet_id: "0",
      )
response1 = service.copy_spreadsheet(spreadsheet_id,gid,request)

puts response1.to_json

This always fails with the following error -
/usr/local/lib/ruby/gems/3.1.0/gems/google-apis-core-0.4.2/lib/google/apis/core/http_command.rb:229:in `check_status': badRequest: Invalid destinationSpreadsheetId [0] (Google::Apis::ClientError)
    from /usr/local/lib/ruby/gems/3.1.0/gems/google-apis-core-0.4.2/lib/google/apis/core/api_command.rb:134:in `check_status'

Would be great if someone can help me on how to use this properly, also if there's a better way to download/export a single sheet from a spreadsheet in Ruby let me know.

A: Answer for question 1

This always fails with the following error -

  /usr/local/lib/ruby/gems/3.1.0/gems/google-apis-core-0.4.2/lib/google/apis/core/http_command.rb:229:in `check_status': badRequest: Invalid destinationSpreadsheetId [0] (Google::Apis::ClientError)
  from /usr/local/lib/ruby/gems/3.1.0/gems/google-apis-core-0.4.2/lib/google/apis/core/api_command.rb:134:in `check_status'

Would be great if someone can help me on how to use this properly,

When I saw your error message and your script, I thought that destination_spreadsheet_id: "0", is not correct. In this case, please set the destination Spreadsheet ID. When this is reflected in your script, it becomes as follows.
src_spreadsheet_id = "###" # Please set the source Spreadsheet ID.
src_sheet_id = "###" # Please set the sheet ID of the source Spreadsheet.
dst_spreadsheet_id = "###" # Please set the destination Spreadsheet ID.

request = Google::Apis::SheetsV4::CopySheetToAnotherSpreadsheetRequest.new(
  destination_spreadsheet_id: dst_spreadsheet_id,
)
response1 = service.copy_spreadsheet(src_spreadsheet_id,src_sheet_id,request)
puts response1.to_json

Answer for question 2

I'm trying to retrieve a single sheet from a google spreadsheet in excel format, I have all the access setup correctly and can run different google sheet v4 api functions on it.

also if there's a better way to download/export a single sheet from a spreadsheet in Ruby let me know.

In this case, how about the following sample script? In this script, a XLSX data including the specific sheet is downloaded using the endpoint of https://docs.google.com/spreadsheets/d/{spreadsheetId}/export?format=xlsx&gid={sheetId}. So, please set your Spreadsheet ID and sheet ID to the URL. And, in this case, the access token is retrieved from service you are using.
url = 'https://docs.google.com/spreadsheets/d/{spreadsheetId}/export?format=xlsx&gid={sheetId}'
filename = 'sample.xlsx' # Please set the saved filename.

access_token = service.request_options.authorization.access_token
open(
  url,
  "Authorization" => "Bearer " + access_token,
  :redirect => true
) do |file|
  open(filename, "w+b") do |out|
    out.write(file.read)
  end
end

*

*When this script is run, the specific sheet of sheetId of spreadsheetId is downloaded as a XLSX data and save it.

*This script uses require "open-uri".

Note:

*

*When the Spreadsheet is downloaded as a XLSX data, when an error related to the scope, please add https://www.googleapis.com/auth/drive.readonly to the scopes and reauthorize again. By this, the script works.

Reference:

*

*Method: spreadsheets.sheets.copyTo


text:
Q: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'C3714552' in 'where clause' Statement st1 = conn.createStatement();
ResultSet rs2 = st1.executeQuery("
   SELECT cui_2
   FROM diagnostico.disease_has_symptom, diagnostico.symptom
   WHERE(
      `symptom`.`cui` = `disease_has_symptom`.`cui_2` AND
      `symptom`.`cui` = " + sintomas.pop() + ");
");

I dont know why i get this error msg...

A: As @Brad indicates, your main issue involves confusing quotes where `symptom`.`cui` = " + sintomas.pop() + "); should be: `symptom`.`cui` = ' + sintomas.pop() + ');.
Why is this the case? According to the SQL-ANSI 92 (an older version of the formal, industry standard of the SQL language that most RDBMS's adhere to including SQL Server, Oracle, Postgres, MySQL, etc.), single quotes and double quotes are used for different purposes.
Double quotes are used for identifiers including column and table names such as "symptom"."cui".
Under,  section 5.2  and  of SQL-92 doc, below is the function definition of the delimited identifier:
<delimited identifier> ::=
   <double quote> <delimited identifier body> <double quote>

Below are few common uses of this type:

*

*Double quotes allow spaces, according to 5.2 - Syntax Rules
2) With the exception of the <space> character explicitly contained
    in <timestamp string> and <interval string> and the permitted
    <separator>s in <bit string literal>s and <hex string literal>s,
    a <token>, other than a <character string literal>, a <national
    character string literal>, or a <delimited identifier>, shall not
    include a <space> character or other <separator>.

*Double quotes impose case sensitivity, compared to regular identifiers:
13)A <regular identifier> and a <delimited identifier> are equivalent
    if the <identifier body> of the <regular identifier> (with
    every letter that is a lower-case letter replaced by the equiva-
    lent upper-case letter or letters) and the <delimited identifier
    body> of the <delimited identifier> (with all occurrences of
    <quote> replaced by <quote symbol> and all occurrences of <dou-
    blequote symbol> replaced by <double quote>), considered as
    the repetition of a <character string literal> that specifies a
    <character set specification> of SQL_TEXT and an implementation-
    defined collation that is sensitive to case, compare equally
    according to the comparison rules in Subclause 8.2, "<comparison
    predicate>".

However, some RDBMS's have their own escaping symbols for special characters, spaces, and reserved words which are not ANSI standards. For example, SQL Server can use square brackets [...]; and MySQL can use backticks `...`.

Single quotes are used to enclose string literals within char, varchar, text data type columns such as 'C3714552'. Your error message is raised because you use double quotes and the MySQL engine is then looking for a column identifier since you wrap the value in double quotes.
Under 5.3  of SQL-92 doc, below is the definition of a string literal (no double quote present):
 <character string literal> ::=
      [ <introducer><character set specification> ]
      <quote> [ <character representation>... ] <quote>
        [ { <separator>... <quote> [ <character representation>... ] <quote> }... ]

And under 5.3 - Syntax Rules:
 1) In a <character string literal> or <national character string
    literal>, the sequence:

      <quote> <character representation>... <quote>
      <separator>... <quote> <character representation>... <quote>

    is equivalent to the sequence

      <quote> <character representation>... <character representa-
      tion>... <quote>

With that said, MySQL provides various non-ANSI modes which may use double quotes for string literals. But possibly backend APIs like JDBC or ODBC, drivers default to ANSI standards.


text:
Q: Creating div and adding a background image to it I've managed to make a div in the place where I wanted it to be, but when it comes to adding a background image, I just can't do it.
I'm creating divs with the loop and then I'm trying to add a background image to it in the same loop. I don't know if that's the problem or something else, if that's the case, please help me make another.
I tried doing something like itemContainer[i] but I can't get that to work either.
Update: the reason is that my array is empty, don't really know what I'm doing wrong though.
var cicon = [];

$.ajax({
    url: '/json/test.json',
    dataType: 'json',
    type: 'get',
    cache: false,
    success: function(data) {
        $(data.test).each(function(index, value) {
            cicon.push(value.Icon);
            /*console.log(value.Icon) works here,
            so there's something wrong when I'm adding it to the array.*/
        });
    }
});

for (var i = 0, n = 10; i < n; i++) {
    var itemContainer = document.createElement("div");
    itemContainer.id = "div" + i;
    itemContainer.innerHTML = "item" + i;

    itemContainer.style.width = "86px";
    itemContainer.style.height = "86px";
    itemContainer.style.margin = "5px";
    itemContainer.style.border = "2px solid black";
    itemContainer.style.borderRadius = "10px";
    itemContainer.style.float = "left";

    var iconstring = 'url(\'' + cicon[i] + '\')';
    itemContainer.style.backgroundSize = "100% 100%";
    itemContainer.style.backgroundImage = iconstring;

    document.getElementById('page').appendChild(itemContainer);
}

If anyone is wondering, the array contains urls that look like this: https://steamcdn-a.akamaihd.net/apps/440/icons/earbuds.f6dc85683202f2530ae8728880f4a47d4b013ea8.png

A: If you re-declare:
var cicon = [];

you are simply emptying the array variable. (how do i empty an array in javascript)
Example:

var cicon = [];

function doWork() {
  for (var i = 0; i < cicon.length; i++) {
    var itemContainer = document.createElement("div");
    itemContainer.id = "div" + i;
    itemContainer.innerHTML = "item" + i;

    itemContainer.style.width = "86px";
    itemContainer.style.height = "86px";
    itemContainer.style.margin = "5px";
    itemContainer.style.border = "2px solid black";
    itemContainer.style.borderRadius = "10px";
    itemContainer.style.float = "left";

    var iconstring = 'url(\'' + cicon[i] + '\')';
    itemContainer.style.backgroundSize = "100% 100%";
    itemContainer.style.backgroundImage = iconstring;

    document.getElementById('page').appendChild(itemContainer);
  }
}
$(function () {
  $.ajax({
    url: '/json/BotCopper.json',
    dataType: 'json',
    type: 'get',
    cache: false,
    success: function (data) {
      $(data.BotCopper).each(function (index, value) {
        cicon.push(value.Icon);
        doWork();
      });
    },
    error: function (jqXHR, textStatus, errorThrown) {
      // this is only for test
      cicon = ['https://rawgit.com/Pixabay/jQuery-flexImages/master/images/1.jpg', 'https://rawgit.com/Pixabay/jQuery-flexImages/master/images/2.jpg',
               'https://rawgit.com/Pixabay/jQuery-flexImages/master/images/3.jpg', 'https://rawgit.com/Pixabay/jQuery-flexImages/master/images/4.jpg',
               'https://rawgit.com/Pixabay/jQuery-flexImages/master/images/5.jpg', 'https://rawgit.com/Pixabay/jQuery-flexImages/master/images/6.jpg',
               'https://rawgit.com/Pixabay/jQuery-flexImages/master/images/7.jpg', 'https://rawgit.com/Pixabay/jQuery-flexImages/master/images/8.jpg',
               'https://rawgit.com/Pixabay/jQuery-flexImages/master/images/9.jpg', 'https://rawgit.com/Pixabay/jQuery-flexImages/master/images/10.jpg'];
      doWork();
    }
  });
});

Instead, removing the line:
var cicon = [];

the result is:

window.onload = function() {
            var cicon = ['https://rawgit.com/Pixabay/jQuery-flexImages/master/images/1.jpg', 'https://rawgit.com/Pixabay/jQuery-flexImages/master/images/2.jpg',
                'https://rawgit.com/Pixabay/jQuery-flexImages/master/images/3.jpg', 'https://rawgit.com/Pixabay/jQuery-flexImages/master/images/4.jpg',
                'https://rawgit.com/Pixabay/jQuery-flexImages/master/images/5.jpg', 'https://rawgit.com/Pixabay/jQuery-flexImages/master/images/6.jpg',
                'https://rawgit.com/Pixabay/jQuery-flexImages/master/images/7.jpg', 'https://rawgit.com/Pixabay/jQuery-flexImages/master/images/8.jpg',
                'https://rawgit.com/Pixabay/jQuery-flexImages/master/images/9.jpg', 'https://rawgit.com/Pixabay/jQuery-flexImages/master/images/10.jpg'];

            for (var i = 0, n = 10; i < n; i++) {
                var itemContainer = document.createElement("div");
                itemContainer.id = "div" + i;
                itemContainer.innerHTML = "item" + i;

                itemContainer.style.width = "86px";
                itemContainer.style.height = "86px";
                itemContainer.style.margin = "5px";
                itemContainer.style.border = "2px solid black";
                itemContainer.style.borderRadius = "10px";
                itemContainer.style.float = "left";

                var iconstring = 'url(\'' + cicon[i] + '\')';
                itemContainer.style.backgroundSize = "100% 100%";
                itemContainer.style.backgroundImage = iconstring;

                document.getElementById('page').appendChild(itemContainer);
            }
        }

A: There is nothing wrong with your script but you need elements in cicon. e.g
var cicon = ["url1","url2",...];
Check here for a working example: Div Background image


text:
Q: How to block/blacklist a spam server via SPF record I have an SPF record:
v=spf1 include:_spf.google.com ip4:70.xx.xx.xx -all

I had the default from Google of
v=spf1 include:_spf.google.com ~all

I've been moving away from this default in an effort to use SPF to prevent some spammer in Iran from continuing to send messages that, when they hit a bogus address, bounce to me with messages like:

Received-SPF: neutral (google.com: 2.191.xx.xx is neither permitted nor denied by best guess record for domain of [jimmy@somedomain.ca]) client-ip=2.191.xx.xx;

That message implies there's a way of denying the spammer's IP, but I've failed to find it, so I'm ultimately unsure.
Any tips? I'd like this spammer to be denied by my SPF directly or indirectly.
Update: Added full, unaltered message I'm trying to react to (below)
Delivered-To: jimmy@somedomain.ca
Received: by 10.28.62.13 with SMTP id l13csp432424wma;
        Sat, 22 Oct 2016 05:10:20 -0700 (PDT)
X-Received: by 10.99.104.196 with SMTP id d187mr9004304pgc.26.1477158220522;
        Sat, 22 Oct 2016 05:10:20 -0700 (PDT)
Return-Path: <>
Received: from mail-pf0-x241.google.com (mail-pf0-x241.google.com. [2607:f8b0:400e:c00::241])
        by mx.google.com with ESMTPS id hf1si1759156pac.263.2016.10.22.05.10.20
        for <jimmy@somedomain.ca>
        (version=TLS1_2 cipher=ECDHE-RSA-AES128-GCM-SHA256 bits=128/128);
        Sat, 22 Oct 2016 05:10:20 -0700 (PDT)
Received-SPF: pass (google.com: best guess record for domain of postmaster@mail-pf0-x241.google.com designates 2607:f8b0:400e:c00::241 as permitted sender) client-ip=2607:f8b0:400e:c00::241;
Authentication-Results: mx.google.com;
       dkim=pass header.i=@googlemail.com;
       spf=pass (google.com: best guess record for domain of postmaster@mail-pf0-x241.google.com designates 2607:f8b0:400e:c00::241 as permitted sender) smtp.helo=mail-pf0-x241.google.com;
       dmarc=pass (p=QUARANTINE dis=NONE) header.from=googlemail.com
Received: by mail-pf0-x241.google.com with SMTP id r16so11229439pfg.3
        for <jimmy@somedomain.ca>; Sat, 22 Oct 2016 05:10:20 -0700 (PDT)
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed;
        d=googlemail.com; s=20120113;
        h=mime-version:from:to:subject:message-id:date;
        bh=hC195D3nA0Uzbsy/ut7vMIZ53a6ExjkByblQBH/81WQ=;
        b=AJOIjSrQPo4+I5fbjmy+4QU7BBVFtRorLh4NYVEZv0zMY5dYn9OMh4pVRRiQoSN4JE
         k0JZJbBzkvPNGXD0ImqQ+cRPD6/Q9yN+QjbRJksR91dJvO2ZeM36OLsY7erIbOYgq1rz
         H80waLIVDDJSRZv2r4zvFnX9K6hE6fZDbDG7x3jKRkGnIzQk2Z1aQ/TGPTz8parrQJrT
         hryzTMSw7T5DKioVYElBpH/wlS8HMaoL2g023KzBtpwLrfkbFE3zeTv0GTryhEeunONH
         +UPEvLr+th5IKpG4VZlrGu17Vz4MKgJgB30g+KGu/Ljbzi/ffLSpSFkN7hZvs2mmBpY+
         PoRA==
X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed;
        d=1e100.net; s=20130820;
        h=x-gm-message-state:mime-version:from:to:subject:message-id:date;
        bh=hC195C3nA0Uzbsy/ut7vMKZ43a6ExjjByblQBH/81WQ=;
        b=HTTQdb/I0eBlF6Q3o0z/wf24aSyu2lvlvIkpoC4Ov+l7c+ruXRnzT5mkUMWiDFCr/w
         LuDQcy7SluQrrnWsCm1k87F4gsUz320Zvb9lCEBqB4FnN37e521tP/C++4tzv6tA09Sd
         W5Wpsk38bHYj5jesKABb0k0Nj4tmS39j7h18BqTY0fnCHjb03pLJNGA1hmACX84Clf27
         bhsCyMhb5z6L7t5UOYTwQ95e2Vlx6jQH2P/h9iKyI+UnpoMOCe9grbvblSkdDiWTTMXR
         5G9KhdrTUmIBfrj+VlhZQoPRXjEjENeD4XEAZ1E4e3lBJfgGbg9Jg6N6PwpxFbnlGReW
         gwHA==
X-Gm-Message-State: ABUngvdfy0M/HHPXzmBpM3vEavjKEG5m35WPLvqH5SEh5U6PEOqEaJ7yK/eqjzO7jzkY1v9GbShSkKocgRqx1k3N1bmPLGh0
X-Received: by 10.99.110.142 with SMTP id j136mr8866332pgc.132.1477138220162;
        Sat, 22 Oct 2016 05:10:20 -0700 (PDT)
MIME-Version: 1.0
Return-Path: <>
Received: by 10.99.110.142 with SMTP id j136mr8914431pgc.132; Sat, 22 Oct 2016 05:10:20 -0700 (PDT)
From: Mail Delivery Subsystem <mailer-daemon@googlemail.com>
To: jimmy@somedomain.ca
Subject: Delivery Status Notification (Delay)
Message-ID: <001a11482caae59c5e053f730a8e@google.com>
Date: Sat, 22 Oct 2016 12:10:20 +0000
Content-Type: text/plain; charset=UTF-8

This is an automatically generated Delivery Status Notification

THIS IS A WARNING MESSAGE ONLY.

YOU DO NOT NEED TO RESEND YOUR MESSAGE.

Delivery to the following recipient has been delayed:

     samantha.bowmer@kojo.com.au

Message will be retried for 4 more day(s)

Technical details of temporary failure:
The recipient server did not accept our requests to connect. Learn more at https://support.google.com/mail/answer/7720
[210.5.32.9 210.5.32.9: generic::failed_precondition: connect error (0): error]

----- Original message -----

X-Gm-Message-State: ABUngvdKe24Xp8DT1rP2gApcFad5/HjrNajRrB9UWHnLxPY9Cmcnd7WyG1oLjYpJrvk4WmDa+0noZVd+uXaMy0PzgG1WVtzkSWXlgEFBYAOKWZTeGeIEOnQJPFBFZJuzwxnkd+KVKcW5
X-Received: by 10.99.110.142 with SMTP id j136mr16455830pgc.132.1476957867242;
        Thu, 20 Oct 2016 03:04:27 -0700 (PDT)
X-Received: by 10.99.110.142 with SMTP id j136mr16455815pgc.132.1476957867120;
        Thu, 20 Oct 2016 03:04:27 -0700 (PDT)
Return-Path: <jimmy@somedomain.ca>
Received: from [2.191.29.134] ([2.191.29.134])
        by mx.google.com with ESMTP id z80si44284204pfj.251.2016.10.20.03.04.25
        for <samantha.bowmer@kojo.com.au>;
        Thu, 20 Oct 2016 03:04:26 -0700 (PDT)
Received-SPF: neutral (google.com: 2.191.29.134 is neither permitted nor denied by best guess record for domain of james.snell@dawning.ca) client-ip=2.191.29.134;
Authentication-Results: mx.google.com;
       spf=neutral (google.com: 2.191.29.134 is neither permitted nor denied by best guess record for domain of james.snell@dawning.ca) smtp.mailfrom=jimmy@somedomain.ca
Message-ID: <233E36AEEE2BA6766B63FBEB0EF3233E@6C2L74D>
From: <jimmy@somedomain.ca>
To: <samantha.bowmer@kojo.com.au>
Subject: Re: Salary [$1500 /week]
Date: 20 Oct 2016 15:04:13 +0200
MIME-Version: 1.0
Content-Type: multipart/alternative;
    boundary="----=_NextPart_000_0027_01D22AD6.01109020"
X-Priority: 3
X-MSMail-Priority: Normal
Importance: Normal
X-Mailer: Microsoft Windows Live Mail 16.4.3505.912
X-MimeOLE: Produced By Microsoft MimeOLE V16.4.3505.912

Dear samantha.bowmer,

We are looking for employees working remotely.

My name is Thanh, I am the personnel manager of a large International company.
Most of the work you can do from home, that is, at a distance.

Salary is $2900-$5100.

If you are interested in this offer, please visit
Our Site

Have a nice day!

A: SPF doesn't mean do not deliver the email, it just's a flag that says to "Hard Fail" (-all) the message, which can make it land in the spam folder, which is based on the ESP.
If you enable DMARC with a Reject Policy, then you will 100% cause the message to be rejected and not delivered to those ESP that respect a DMARC Policy. GMAIL is one of those places.
Enabling a DMARC record is just as simple as adding an SPF record, it's based completely on a DNS Entry just like SPF.
In your case your DMARC Record will be fairly simple.
_dmarc.somedomain.ca. IN TXT "v=DMARC1; p=reject; sp=none; rf=afrf; pct=100; ri=86400"

If you want the reports, just add the RUA and RUF information, to the record above. You can DMARC Generators to generate the record for you.


text:
Q: Proof of $\overline{A} = \bigcap_{U\in\mathfrak{U}}(A + U) = \bigcap_{U\in\mathfrak{U}}\overline{A + U}$ Proposition.
Let $G$ be an abelian (probably not Hausdorff) topological group, let $A$ be a subset of $G$, and let $\mathfrak{U} = \{U\subseteq G \mbox{ : neighbourhood of }0\}$. Then, the closure $\overline{A}$ is written as
$$
\overline{A} = \bigcap_{U\in\mathfrak{U}}(A + U) = \bigcap_{U\in\mathfrak{U}}\overline{A + U}.
$$
Question.
I want to prove $\bigcap\overline{A + U}\subseteq \bigcap(A + U)$. Let $x\in \bigcap\overline{A + U}$, and let $U\in\mathfrak{U}$. There exists a  $U'\in \mathfrak{U}$ such that $U' + U' \subseteq U$. A PDF I'm reading says that $\overline{A + U'}\subseteq A + U' + U'$, why?

A: Let $x\in \overline{A + U'}$, then $x - U'$ is a neighbourhood of $x$. Therefore $(x - U')\cap (A + U')\neq\varnothing$, and there exists $u$, $v\in U'$, and $a\in A$ such that $x - u = a + v$. Hence $x = a + u + v\in A + U' + U'$.


text:
Q: A curious plot of Primes (II) Here is the plot of a function $f(x)$ such that:
$$
f(x) = \frac {P_ {\lfloor 2 x \rfloor}} {P_ {\lfloor 2 x \rfloor -  1}}
$$
where $P_k$ is the $k^{\mathrm{th}}$ Prime Number for x in range [1,300].

The curves are in the form $1 + \frac {1} {a x^b}$, with $a,b\in\mathbb {R}$ and where I chose arbitrarily $a$ and $b$, $b\simeq 1.22$ in the image above.
Personally, I was very surprised whith what seems very regular shapes occurring again and again along the curves.
Can someone explain this?
I deleted the first post about this, because it seems more like a Mathematica bug than something else, but I cannot find what's wrong.
Here is the Mathematica code:
Block[{x},
Module[{ a, b, c, xa, xb, plotall, plots0, plots1},
a = Prime[Floor[2*x - 1]];
b = Prime[Floor[2*x]];
xa = 1; xb = 300; c = 1.22;
plots0 = { b/a};
plots1 = {1 + 1/2.21/x^c, 1 + 1/1.1/x^c, 1 + 1/0.725/x^c,
1 + 1/0.435/x^c, 1 + 1/0.31/x^c, 1 + 1/0.195/x^c,
1 + 1/0.126/x^c  };
plotall = Join @@ {plots0, plots1};
Panel@Plot[  Tooltip@plotall, {x, xa, xb} , AxesLabel -> {x, y}]
]
]

As also suggested, here is the plot of:
$$
f (x) = \frac {P_ {\lfloor x \rfloor}} {P_ {\lfloor x \rfloor - 1}}
$$

and the interactive Mathematica code:
Block[{x},
Manipulate[
Module[{a, b, xa, xb, plotall, plots0, plots1},
a = Prime[Floor[x] - 1];
b = Prime[Floor[x]];
xa = 2; xb = 300;
plots0 = { b/a};
plots1 = { 1 + 1/r1/x^c1 };
plotall = Join @@ {plots0, plots1};
Plot[ Tooltip@plotall, {x, xa, xb} , AxesLabel -> {x, y}]
]
, Style["Global Options", Bold, "Panel"]
, {{r1, 0.83}, 0, 3, Appearance -> "Open"}
, {{c1, 1.25}, 0, 5, Appearance -> "Open"}
]
]

Since Julian Aguirre's answer, I just wanted to add the following graph, where the curves are in the form $1+ \frac {7} {4}.\frac {n} {x\text { Log} (x)}$ for $n$ integer in range[1,10]...

A: What you see is due to the gaps between prime numbers.
$$
\frac{P_{2k}}{P_{2k-1}}=1+\frac{P_{2k}-P_{2k-1}}{P_{2k-1}}.
$$
The curves you see are formed by primes with gaps $2$, $4$, $6$, \dots
¿What can we say about the curves? Using the Prime Number Theorem, the primes with gap $g$, where $g$ is a positive even number, lie close to the prph of the function
$$
f_g(x)=1+\frac{g}{(2\,x-1)\ln(2\,x-1)}.
$$
You can see it in the following picture, where points are colores according to the gap:


text:
Q: Android admob show banner ad over webview I want to show a banner ad over webview. But don't know how to do.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_ptv"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.techndroid.cricketlivestreaming.Ptv">

    <com.google.android.gms.ads.AdView
        android:id="@+id/adView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        ads:adSize="BANNER"
        ads:adUnitId="@string/banner_ad_unit_id" />

    <WebView
        android:layout_below="@+id/adView"
        android:id="@+id/webStream"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>

I want ad to show top of the layout.
I think it goes behind the webview. I need to show over webview

A: You can show in RelativeLayout too:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:id="@+id/main"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <WebView
        android:id="@+id/myWebView"
        android:layout_above="@+id/adView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

    <com.google.android.gms.ads.AdView
        android:id="@+id/adView"
        ads:adSize="BANNER"
        ads:adUnitId="ca-app-pub-3940256099942544/6300978111"
        android:layout_width="match_parent"
        android:background="@android:color/transparent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true">
    </com.google.android.gms.ads.AdView>

</RelativeLayout>

In java, just write:
    AdView mAdView = (AdView) findViewById(R.id.adView);
    AdRequest adRequest = new AdRequest.Builder().build();
    mAdView.loadAd(adRequest);

A: For the solution you can use Frame Layout
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_ptv"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.techndroid.cricketlivestreaming.Ptv">

<com.google.android.gms.ads.AdView
    android:id="@+id/adView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    ads:adSize="BANNER"
    ads:adUnitId="@string/banner_ad_unit_id" />

<WebView
    android:layout_below="@+id/adView"
    android:id="@+id/webStream"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

</FrameLayout >

A: <?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:ads="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <WebView

            android:id="@+id/webStream"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

    </LinearLayout>

    <com.google.android.gms.ads.AdView
        android:id="@+id/adView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        ads:adSize="BANNER"
        ads:adUnitId="@string/banner_ad_unit_id" />
</FrameLayout>


text:
Q: How do I specify CSS classes for specific rows in a GridView? I am creating a SharePoint web part in C# and part of it outputs a GridView control to the page. While I can get fairly extensive control over the way it is displayed by setting the CSS class of the GridView itself, what I would really like to do is be able to specify classes to certain specific td elements. I'm not sure how to go about doing this, or if it would be done at the time that the GridView is being populated with rows, or at the time the GridView is added to the page.
In pseudocode, what I had essentially envisioned was to be able to say something like gridView.Row[4].CssClass = "header", which would set the td of the fifth row in the GridView to the class "header."
I've looked into using the RowDataBound event, so I just used the following to test it:
protected void outputGrid1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    e.Row.CssClass = "outputHeader";
}

It's probably my misunderstanding of how to use that properly, but it doesn't appear to do anything. I thought it would set all of the rows to the class "header," and if it had, I was going to work on my logic from there, but I can't even get that to work. Thanks for any help anyone can provide!

A: I do something similar with RowDataBound:
if (e.Row.RowType == DataControlRowType.DataRow)
{
    // Check the XXXX column - if empty, the YYYY needs highlighting!
    if (e.Row.Cells[6].Text == " ")
    {
       e.Row.CssClass = "highlightRow"; // ...so highlight it
    }
}

One way to check that what you are doing is correct is to monitor your html output via the browser... something like Firebug really helps.
Here's some sample CSS, where we assign the CssClass 'dataGrid' to the Grid:
/* Used to highlight rows */
table.dataGrid tr.highlightRow td
{
    background-color: #FF6666;
    border-bottom: 1px solid #C0C0FF;
}

Update: Wiring all this up: I use auto-wire-up on the aspx page. Your page declaration looks something like this:
<%@ Page Language="C#" MasterPageFile="~/XXXXXX.master" AutoEventWireup="true" CodeBehind="YYYY.aspx.cs" Inherits="ZZZ.ZZZ.AAAAAA" Title="View Blah" %>

This setting on the page allows you to use the UI to connect up the events. Click the grid, select the properties, click the lightning-strike icon, and under the RowDataBound event, select your method. All this does behind the scenes is add an attribute to the DataGridView, thus:
        <asp:GridView ID="uiActionGridView" runat="server" AllowSorting="True" AutoGenerateColumns="False"
        OnRowDataBound="uiActionGridView_RowDataBound" OnDataBound="uiActionGridView_DataBound">

*

*this shows two events being wired-up, the DataBound and RowDataBound events.

This is what I do using VS2005 and it all seems to 'just work'. The only thing that I can think you are experiencing is that you are manually binding the event after the databind has occurred.

A:
Optional! you can also add bootstrap class in code behind like...

protected void gvEmpContactsHistory_SelectedIndexChanged(object sender, EventArgs e)
    {
        string val = Convert.ToDateTime(gvEmpContactsHistory.SelectedDataKey.Value).ToString("dd-MM-yyyy hh:mm:ss", new System.Globalization.CultureInfo("en-US"));
        GetEmployeeDetail(val);

        foreach (GridViewRow row in gvEmpContactsHistory.Rows)
        {
            if (row.RowIndex == gvEmpContactsHistory.SelectedIndex)
            {
                row.ToolTip = string.Empty;
                row.Attributes.Add("class", "btn-success");
            }
            else
            {
                row.ToolTip = "Click to select this row.";
                row.Attributes.Add("class", "btn-outline-success");
            }
        }
    }


text:
Q: How to tackle Scala source incompatibilities in 2.8.0? There are a few cases of source incompatibilities with Scala 2.8.0. For example, creating an anonymous Seq once required defining the abstract def elements : Iterator[A], which is now called def iterator : Iterator[A].
To me, a "brute force" solution is to create two branches that align to the different major scala versions.
Are there general techniques so that code like this will compile under both systems?
// Note: this code resembles techniques used by xml.NodeSeq
trait FooSeq extends Seq[ Foo ] {
   def internal : Seq[ Foo ]
   def elements = internal.elements
   def iterator = internal.iterator // Only compiles in 2.8
                                    // need to remove for 2.7.X
}

A: There are a few cases where usage is simply different and you must change.  But in almost all cases--such as the elements code above--the 2.7 style is simply deprecated in 2.8, not gone altogether.  If you're okay leaving your 2.8 users with deprecation warnings (edit: if they compile your code, otherwise you'll just have the warnings yourself), just implement the new features in terms of the old:
def iterator = internal.elements

Otherwise, I would recommend what you call the brute force solution.  Use a sufficiently clever VCS so that you don't actually have to write much code twice (Git, Bazaar, Mercurial) and branch.


text:
Q: UNC share directory does not exist I have a C# process that needs to read a file existing in a share directory on a remote server.
The below code results in "Share does not exist." being written to the console.
string fileName = "someFile.ars";
string fileLocation = @"\\computerName\share\";
if (Directory.Exists(fileLocation))
{
    Console.WriteLine("Share exists.");
}
else
{
    Console.WriteLine("Share does not exist.");
}

The process is run under an AD user account and the same account is granted Full Control permissions on the share directory. I can successfully map the share as a network drive on the machine the process resides on and can copy files to/from the directory. Any ideas on what I'm missing?

A: Use File.Exists rather than Directory.Exists.
Plus, you may want to be somewhat platform-agnostic and use the canonical Path.Combine as such:
string fileName = "someFile.ars";
string fileServer = @"\\computerName";
string fileLocation = @"share";
if (File.Exists(Path.Combine(fileServer, fileLocation, fileName)))
{
    Console.WriteLine("Share exists.");
}
else
{
    Console.WriteLine("Share does not exist.");
}


text:
Q: How to ensure library calls execute in order they are called     WindowManager.setCurrentWindow(a.getWindow());
    System.err.println("Current window is " + WindowManager.getCurrentWindow());
    WindowManager.setCurrentWindow(b.getWindow());
    System.err.println("Current window is " + WindowManager.getCurrentWindow());

WindowManager is a class defined in the ij package [ImageJ's java API - https://imagej.nih.gov/ij/developer/api/ij/WindowManager.html#setCurrentWindow--], both methods called here are static methods in the WindowManager class, my program is only written in one thread.
The code above varies between printing 'a' 'a' and 'a' 'b'. My assumption here is that WindowManager.setCurrentWindow(ImageWindow x) must be executing in another thread, and it returns control to my thread before it has finished.
Is there a way to ensure the current thread won't continue until the first method has finished it's execution? -- I think I could use a while loop, but I was hoping there would be a more efficient solution than that.


text:
Q: PreviewPageCountType.Final vs PreviewPageCountType.Intermediate what is the difference in the behavior of the two values of the PreviewPageCountType

A: PreviewPageCountType is used in PrintDocument method SetPreviewPageCount when your application tells Windows how many pages your can and/or want to show on the preview dialog.
In general, preparing print pages might take significant time, while Win Store Application UI is supposed to be very responsive and shouldn't wait more than necessary to respond to user requests.
For a developer, that means that you probably want to prepare preview pages in a background task. By the time preview flyout dialog needs to show the first page(s) to the user, that task might be only half-done and the number of total pages is yet unknown.
To remedy that, when PrintDocument.Paginate event is processed, you can call SetPreviewPageCount with a number of pages, say N, that are ready to be previewed. You tell Windows that it's not the final amount by PreviewPageCountType.Intermediate. Print preview dialog will hence allow user to see pages 1..N of N.
Once the application knows the exact number of pages, M, it makes another call with PreviewPageCountType.Final and Windows updates preview dialog,  allowing user to see pages 1..M of M.
You can actually do more intermediate updates, and the user will see an increasing number of available preview pages on the preview flyout:
printDocument.Dispatcher.RunAsync(CoreDispatcherPriority.Low, async () =>
{
    for (int i = 1; i < 300; i++)
    {
        printDocument.SetPreviewPageCount(i, PreviewPageCountType.Intermediate);
        await Task.Delay(50); // Simulate page generation delay
    }
    printDoc.SetPreviewPageCount(300, PreviewPageCountType.Final);
});

Now, to tell the truth, as of now my tests show no real difference between Intermediate and Final. However, it's still a good idea to follow the expected pattern, in case future changes make it more strict.


text:
Q: Return one record from a form data source I have a form with an existing data source. This data source has a one to many relationship to another table that is not an existing data source. Even though this second table contains multiple records (one to many), the field in the table that I want is duplicated across all records. Therefore I want to add this second table as a data source, but only return one record from it.
If I add the second table directly, than my form contains a line for each record instead of just one.

A: This problem was solved by creating a view to use as the new datasource. This view defined a calculated column that was based on a method that contained a query string that used TOP 1. The details in much more detail are at Martin Dráb's blog: https://community.dynamics.com/ax/b/goshoom/archive/2015/06/29/join-first-line-in-ax-2012.

A: Use the property LinkType=ExistJoin on the datasource for your second table.
See the TransactionLog form for example.


text:
Q: "cannot open file userpref.blend@ for writing: Permission denied" in blender I'm using blender 2.69, installed via software centre, and when I save my user preference through File -> User Preferences and click on "Save User Settings" there is a message
"cannot open file /home/ganez/.config/blender/2.69/config/userpref.blend@ for writing permission denied"
I have checked to the path /home/ganez/.config/blender/2.69/config/ and there is no userpref.blend file present.
PS: I think this has something to do with file permission for that config folder and I have no idea on how to use the chmod command. So any advise?
Thank you in advance.

A: I just ran into the same bug. I suspect it may have occurred during a recent crash, but I cannot confirm this.
You may try to rename the folder (close Blender first):
mv ~/.config/blender ~/.config/blender.old

Then open Blender. When I tried this, Blender regenerated the folder with the proper permissions.
Generally, it is recommended to avoid running programs as root. With such a large code-base, a program is bound to have some areas of undefined behavior (bugs) that even if not malicious, could be dangerous to your system.

A: OK now. I just figured it out myself for now(Answering my own question).
We have to run the program as root from the terminal.
gksudo blender

and then there won't be any problem as permission denied.

A: A solution is to use chown command to take ownership of the interested folder. From terminal: navigate to the ~/.config/blender folder; check current permissions with dir -ls. For example, in my case, the folder for blender 2.72 was owned by root. So I fixed with:
sudo chown -R myusername:myusergroup /2.72

Where myusername and myusergroup are my actual Linux user name and group.


text:
Q: Sum up values of identical objects' property in Javascript array I have the following array :
[
 { name: "iPhone 12", quantity: 12, price: 325, … },
 { name: "iPhone 12", quantity: 4, price: 325, … },
 { name: "iPhone 13", quantity: 2, price: 525, … },
 { name: "iPhone 12", quantity: 2, price: 325 },
 { name: "iPhone 13", quantity: 3, price: 525 },
 { name: "iPhone SE", quantity: 2, price: 59 }
]

And I want to sum the quantity properties of each object in order to have an array with distinct elements like this :
[
  { name: "iPhone 12", quantity: 18, price: 325 },
  { name: "iPhone 13", quantity: 5, price: 525 },
  { name: "iPhone SE", quantity: 2, price: 59 }
]

How can I do that?

A: Seems like a good task for Array.prototype.reduce

const data = [{
    name: "iPhone 12",
    quantity: 12,
    price: 325,
  },

  {
    name: "iPhone 12",
    quantity: 4,
    price: 325,
  },

  {
    name: "iPhone 13",
    quantity: 2,
    price: 525,

  },

  {
    name: "iPhone 12",
    quantity: 2,
    price: 325
  },

  {
    name: "iPhone 13",
    quantity: 3,
    price: 525
  },
]
const summed = data.reduce((sum, current) => {
  const item = sum.find(el => el.name === current.name)
  if (item) {
    for (const key in item) {
      if (key === 'name') continue
      item[key] += current[key]
    }
  } else {
    sum.push({ ...current })
  }
  return sum
}, [])

console.log(summed)


text:
Q: What are the values of $a$ for which this integral converges? What are the values of a for which this integral converges?
$$I = \int_{0}^{\infty} \frac{\sin x}{x^a}\,dx.$$
I tried comparing it with the integral $$\int_{0}^{\infty} \frac{1}{x^a}\,dx.$$ but I couldn't get anything out of it.
Any help would be appreciated. :)

A: Firstly let's divide $\int_{0}^{\infty} \frac{\sin x}{x^a}\,dx $ from $0$ to $1$ and from $1$ to $\infty$.
For first lets use, that $\dfrac{\sin x}{x^a}$ for $x \to 0+$ can be majored by
$\dfrac{1}{x^{a-1}}$ and it converges when $a<2$.
Second can be majored by $\dfrac{1}{x^a}$ and absolutely converges when $a>1$. For simple converging is enough $a>0$, as antiderivative of $\sin$ is bounded and $\dfrac{1}{x^a}$ tends to $0$ monotonically.
Joining we come to $0<a<2$.


text:
Q: Can I access a hash stored in html elements data attribute with jquery? I've got several html elements that I'm appending hashes to like so:

  Relevant Content

so that
$(".message").first().data("dependencies")

returns
{'#first':{'equal':'Yes'}}

But as a buddy just pointed out to me, this value is a string. So naturally the filter described below has a hard time with it.
The goal of the filter is to be able to grab elements that have a specified key, in this case "#first".
$el.children().find("*").filter(function(){
    var dependency_hash = $(this).data("dependencies");
    if(dependency_hash != undefined && "#first" in dependency_hash){
      return true
    }
});

Is there a way to access the hash as passed via the data object or is there another way I can structure the data so as to accomplish the same means of being able to select elements based on the key?

A: If you store it as valid JSON, you can parse it, and get is content.

  Relevant Content

var json = $(".message").first().attr("data-dependencies");

// HTML5 browsers
// var json = document.querySelector(".message").dataset.dependencies;

var parsed = $.parseJSON(data);

alert(parsed["#first"].equal); // "Yes"

Or if you use jQuery's .data(), it will parse it automatically.
var parsed = $(".message").first().data("dependencies");

alert(parsed["#first"].equal); // "Yes"

A: Use JSON.parse. There are polyfills if you need support in older browsers.
$el.children().find("*").filter(function(){
    var dependency_hash = $(this).data("dependencies");
    var parsed_hash = JSON.parse(dependency_hash);
    if(parsed_hash != undefined && "#first" in parsed_hash ){
      return true
    }
});

A: You probably want to serialize your data as JSON http://json.org/ and then get it back in JS.
You can use jquery's parser http://api.jquery.com/jQuery.parseJSON/


text:
Q: Open source command line tool for Linux to diff XML files ignoring element order Is there an open source command-line tool (for Linux) to diff XML files which ignores the element order?
Example input file a.xml:
<tag name="AAA">
  <attr name="b" value="1"/>
  <attr name="c" value="2"/>
  <attr name="a" value="3"/>
</tag>

<tag name="BBB">
  <attr name="x" value="111"/>
  <attr name="z" value="222"/>
</tag>
<tag name="BBB">
  <attr name="x" value="333"/>
  <attr name="z" value="444"/>
</tag>

b.xml:
<tag name="AAA">
  <attr name="a" value="3"/>
  <attr name="b" value="1"/>
  <attr name="c" value="2"/>
</tag>

<tag name="BBB">
  <attr name="z" value="444"/>
  <attr name="x" value="333"/>
</tag>
<tag name="BBB">
  <attr name="x" value="111"/>
  <attr name="z" value="222"/>
</tag>

So comparing these 2 files should not output any differences.
I have tried to sort the files with XSLT first:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" encoding="WINDOWS-1252" omit-xml-declaration="no" indent="yes"/>
  <xsl:strip-space elements="*"/>

  <xsl:template match="node()|@*">
    <xsl:copy>
      <xsl:apply-templates select="node()|@*">
        <xsl:sort select="@*" />
      </xsl:apply-templates>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>

But the problem is that for the elements <tag name="BBB"> there is no sorting. They are simply output the order which they are input.
I have already looked at diffXml, xDiff, XMLUnit, xmlstarlet but none of these solve the problem; the diff output should be human readable, e.g. like when using diff.
Any hints on how either the sorting or ignoring element-order diff can be solved? Thanks!

A: I had a similar problem and I eventually found: https://superuser.com/questions/79920/how-can-i-diff-two-xml-files
That post suggests doing a canonical xml sort then doing a diff. Being that you are on linux, this should work for you cleanly. It worked for me on my mac, and should work for people on windows if they have something like cygwin installed:
$ xmllint --c14n a.xml > sortedA.xml
$ xmllint --c14n b.xml > sortedB.xml
$ diff sortedA.xml sortedB.xml

A: You're requesting a sort based on the sequence of attributes in the elements being sorted.  But your top-level tag elements here have only one attribute: name.  If you want multiple tag elements with name="BBB" to sort differently, you need to give them distinct sort keys.
In your example, I'd try something like select="concat(name(), @name, name(*[1]), *[1]/@name)" -- but this is a very shallow key.  It uses values from the first child in the input, but the children may shift position during the process.  You may be able (knowing your data better than I do) to calculate a good key for each element in a single pass, or you may just need several passes.

A: First your XML examples are not valid, because they lack a root element. I added a root element. This is a.xml:
<?xml version="1.0" encoding="UTF-8"?>
<root>
    <tag name="AAA">
        <attr name="b" value="1"/>
        <attr name="c" value="2"/>
        <attr name="a" value="3"/>
    </tag>
    <tag name="BBB">
        <attr name="x" value="111"/>
        <attr name="z" value="222"/>
    </tag>
    <tag name="BBB">
        <attr name="x" value="333"/>
        <attr name="z" value="444"/>
    </tag>
</root>

And this is b.xml:
<?xml version="1.0" encoding="UTF-8"?>
<root>
    <tag name="AAA">
        <attr name="a" value="3"/>
        <attr name="b" value="1"/>
        <attr name="c" value="2"/>
    </tag>
    <tag name="BBB">
        <attr name="z" value="444"/>
        <attr name="x" value="333"/>
    </tag>
    <tag name="BBB">
        <attr name="x" value="111"/>
        <attr name="z" value="222"/>
    </tag>
</root>

You can create a canonical form for the comparison by merging the siblings with the same name attribute and sorting by the tag name and the value.
In order to merge the sibling elements with the same name you have to ignore the elements which name is the same like a preceding sibling and take the remaining. This can be done on the second element level by the following Xpath:
*[not(@name = preceding-sibling::*/@name)]

You have to take the name of those elements in order to select all the child elements which have a parent with this name. After that you have to sort by name and value. This makes it possible to transform both files into this canonical form:
<?xml version="1.0" encoding="WINDOWS-1252"?>
<root>
    <tag name="AAA">
        <attr name="a" value="3"/>
        <attr name="b" value="1"/>
        <attr name="c" value="2"/>
    </tag>
    <tag name="BBB">
        <attr name="x" value="111"/>
        <attr name="x" value="333"/>
        <attr name="z" value="222"/>
        <attr name="z" value="444"/>
    </tag>
</root>

This will do the transformation:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" encoding="WINDOWS-1252" omit-xml-declaration="no" indent="yes"/>
    <xsl:strip-space elements="*"/>
    <xsl:template match="/root">
        <xsl:copy>
                <xsl:copy-of select="@*"/>
                <xsl:for-each select="*[not(@name = preceding-sibling::*/@name)]">
                    <xsl:variable name="name" select="@name"/>
                    <xsl:copy>
                        <xsl:copy-of select="@*"/>
                        <xsl:for-each select="../*[@name = $name]/*">
                            <xsl:sort select="@name"/>
                            <xsl:sort select="@value"/>
                            <xsl:copy>
                                <xsl:copy-of select="@*"/>
                            </xsl:copy>
                        </xsl:for-each>
                    </xsl:copy>
                </xsl:for-each>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

A: You'd have to write your own interpreter to preprocess.  XSLT is one way to do it ... maybe; I'm not an expert in XSLT and I'm not sure you can sort things with it.
Here is a quick and dirty perl script which can do what you want.  Note that it's far far far wiser to use a real XML parser.  I'm not familiar with any, so I'm exposing you to my terrible practice of writing them myself.  Note the comments; you have been warned.
#!/usr/bin/perl

use strict;
use warnings;

# NOTE: general wisdom - do not use simple homebrewed XML parsers like this one!
#
# This makes sweeping assumptions that are not production grade.  Including:
#   1. Assumption of one XML tag per line
#   2. Assumption that no XML tag contains a greater-than character
#      like <foo bar="<oops>" />
#   3. Assumes the XML is well-formed, nothing like <foo><bar>baz</foo></bar>

# recursive function to parse each tag.
sub parse_tag {
  my $tag_name = shift;
  my @level = (); # LOCAL: each recursive call has its OWN distinct @level
  while(<>) {
    chomp;

    # new open tag:  match new tag name, parse in recursive call
    if (m"<\s*([^\s/>]+)[^/>]*>") {
      push (@level, "$_\n" . parse_tag($1) );

    # close tag, verified by name, or else last line of input
    } elsif (m"<\s*/\s*$tag_name[\s>]"i or eof()) {
      # return all children, sorted and concatenated, then the end tag
      return join("\n", sort @level) . "\n$_";

    } else {
      push (@level, $_);
    }
  }
  return join("\n", sort @level);
}

# start with an impossible tag in case there is no root
print parse_tag("<root>");

Save that as xml_diff_prep.pl and then run this:
$ diff -sq <(perl xml_diff_prep.pl a.xml) <(perl xml_diff_prep.pl b.xml)
Files /proc/self/fd/11 and /proc/self/fd/12 are identical

(I used the -s and -q flags to be explicit.  You can use gvimdiff or whatever other utility or flags you like.  Note it identifies the files by file descriptor; that's because I used a bash trick to run the preprocessor command on each input.  They'll be in the same order you specified.  Note that the contents may be in unexpected locations due to the sorting requested by this question.)
To satisfy your "Open Source" "command line tool" request, I hereby release this code as Open Source under the Beerware License (BSD 2-clause, if you think it's worthwhile, you are welcome to buy me a beer).

A: if you wanted to take this to an arbitrary degree, you could implement something that walks the two trees together and decides along the way which elements "match" between the two documents. that'd let you implement the matching logic any way you want. here is an example in xslt 2.0:
<xsl:stylesheet version="2.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:xs="http://www.w3.org/2001/XMLSchema"

                xmlns:set="http://exslt.org/sets"

                xmlns:primary="primary"
                xmlns:control="control"

                xmlns:util="util"

                exclude-result-prefixes="xsl xs set primary control">

    <xsl:output method="text"/>

    <xsl:strip-space elements="*"/>

    <xsl:template match="/">
        <xsl:call-template name="compare">
            <xsl:with-param name="primary" select="*/*[1]"/><!-- first child of root element, for example -->
            <xsl:with-param name="control" select="*/*[2]"/><!-- second child of root element, for example -->
        </xsl:call-template>
    </xsl:template>

    <!-- YOUR SPECIFIC OVERRIDES -->

    <xsl:template match="attr" mode="find-match" as="element()?">
        <xsl:param name="candidates" as="element()*"/>
        <!-- attr matches by @name and @value -->
        <xsl:sequence select="$candidates[@name = current()/@name][@value = current()/@value][1]"/>
    </xsl:template>

    <xsl:template match="tag" mode="find-match" as="element()?">
        <xsl:param name="candidates" as="element()*"/>
        <xsl:variable name="attrs" select="attr"/>
        <!-- tag matches if @name matches and attr counts (matched and unmatched) match -->
        <xsl:sequence select="$candidates[@name = current()/@name]
                                         [count($attrs) = count(util:find-match($attrs, attr))]
                                         [count($attrs) = count(attr)][1]"/>
    </xsl:template>

    <xsl:function name="util:find-match">
        <xsl:param name="this"/>
        <xsl:param name="candidates"/>
        <xsl:apply-templates select="$this" mode="find-match">
            <xsl:with-param name="candidates" select="$candidates"/>
        </xsl:apply-templates>
    </xsl:function>

    <!-- END SPECIFIC OVERRIDES -->

    <!-- compare "primary" and "control" elements -->
    <xsl:template name="compare">
        <xsl:param name="primary"/>
        <xsl:param name="control"/>

        <xsl:variable name="diff">
            <xsl:call-template name="match-children">
                <xsl:with-param name="primary" select="$primary"/>
                <xsl:with-param name="control" select="$control"/>
            </xsl:call-template>
        </xsl:variable>

        <xsl:choose>
            <xsl:when test="$diff//*[self::primary:* | self::control:*]">
                <xsl:text>FAIL</xsl:text><!-- or do something more sophisticated with $diff... -->
            </xsl:when>
            <xsl:otherwise>
                <xsl:text>PASS</xsl:text>
            </xsl:otherwise>
        </xsl:choose>

    </xsl:template>

    <!-- default matching template for elements

         for context node (from "primary"), choose from among $candidates (from "control") which one matches

         (for "complex" elements, name has to match, for "simple" elements, name and value do)

         (override with more specific match pattern if desired)
         -->
    <xsl:template match="*" mode="find-match" as="element()?">
        <xsl:param name="candidates" as="element()*"/>
        <xsl:choose>
            <xsl:when test="text() and count(node()) = 1">
                <xsl:sequence select="$candidates[node-name(.) = node-name(current())][text() and count(node()) = 1][. = current()][1]"/>
            </xsl:when>
            <xsl:when test="not(node())">
                <xsl:sequence select="$candidates[node-name(.) = node-name(current())][not(node())][1]"/>
            </xsl:when>
            <xsl:otherwise>
                <xsl:sequence select="$candidates[node-name(.) = node-name(current())][1]"/>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:template>

    <!-- default matching template for attributes

         for context attr (from "primary"), choose from among $candidates (from "control") which one matches

         (name and value have to match)

         (override with more specific match pattern if desired)
         -->
    <xsl:template match="@*" mode="find-match" as="attribute()?">
        <xsl:param name="candidates" as="attribute()*"/>
        <xsl:sequence select="$candidates[. = current()][node-name(.) = node-name(current())][1]"/>
    </xsl:template>

    <!-- default primary-only template (override with more specific match pattern if desired) -->
    <xsl:template match="@* | *" mode="primary-only">
        <xsl:apply-templates select="." mode="illegal-primary-only"/>
    </xsl:template>

    <!-- write out a primary-only diff -->
    <xsl:template match="@* | *" mode="illegal-primary-only">
        <primary:only>
            <xsl:copy-of select="."/>
        </primary:only>
    </xsl:template>

    <!-- default control-only template (override with more specific match pattern if desired) -->
    <xsl:template match="@* | *" mode="control-only">
        <xsl:apply-templates select="." mode="illegal-control-only"/>
    </xsl:template>

    <!-- write out a control-only diff -->
    <xsl:template match="@* | *" mode="illegal-control-only">
        <control:only>
            <xsl:copy-of select="."/>
        </control:only>
    </xsl:template>

    <!-- assume primary (context) element and control element match, so render the "common" element and recurse -->
    <xsl:template match="*" mode="common">
        <xsl:param name="control"/>

        <xsl:copy>
            <xsl:call-template name="match-attributes">
                <xsl:with-param name="primary" select="@*"/>
                <xsl:with-param name="control" select="$control/@*"/>
            </xsl:call-template>

            <xsl:choose>
                <xsl:when test="text() and count(node()) = 1">
                    <xsl:value-of select="."/>
                </xsl:when>
                <xsl:otherwise>
                    <xsl:call-template name="match-children">
                        <xsl:with-param name="primary" select="*"/>
                        <xsl:with-param name="control" select="$control/*"/>
                    </xsl:call-template>
                </xsl:otherwise>
            </xsl:choose>
        </xsl:copy>

    </xsl:template>

    <!-- find matches between collections of attributes in primary vs control -->
    <xsl:template name="match-attributes">
        <xsl:param name="primary" as="attribute()*"/>
        <xsl:param name="control" as="attribute()*"/>
        <xsl:param name="primaryCollecting" as="attribute()*"/>

        <xsl:choose>
            <xsl:when test="$primary and $control">
                <xsl:variable name="this" select="$primary[1]"/>
                <xsl:variable name="match" as="attribute()?">
                    <xsl:apply-templates select="$this" mode="find-match">
                        <xsl:with-param name="candidates" select="$control"/>
                    </xsl:apply-templates>
                </xsl:variable>

                <xsl:choose>
                    <xsl:when test="$match">
                        <xsl:copy-of select="$this"/>
                        <xsl:call-template name="match-attributes">
                            <xsl:with-param name="primary" select="subsequence($primary, 2)"/>
                            <xsl:with-param name="control" select="remove($control, 1 + count(set:leading($control, $match)))"/>
                            <xsl:with-param name="primaryCollecting" select="$primaryCollecting"/>
                        </xsl:call-template>
                    </xsl:when>
                    <xsl:otherwise>
                        <xsl:call-template name="match-attributes">
                            <xsl:with-param name="primary" select="subsequence($primary, 2)"/>
                            <xsl:with-param name="control" select="$control"/>
                            <xsl:with-param name="primaryCollecting" select="$primaryCollecting | $this"/>
                        </xsl:call-template>
                    </xsl:otherwise>
                </xsl:choose>

            </xsl:when>
            <xsl:otherwise>
                <xsl:if test="$primaryCollecting | $primary">
                    <xsl:apply-templates select="$primaryCollecting | $primary" mode="primary-only"/>
                </xsl:if>
                <xsl:if test="$control">
                    <xsl:apply-templates select="$control" mode="control-only"/>
                </xsl:if>
            </xsl:otherwise>
        </xsl:choose>

    </xsl:template>

    <!-- find matches between collections of elements in primary vs control -->
    <xsl:template name="match-children">
        <xsl:param name="primary" as="node()*"/>
        <xsl:param name="control" as="element()*"/>

        <xsl:variable name="this" select="$primary[1]" as="node()?"/>

        <xsl:choose>
            <xsl:when test="$primary and $control">
                <xsl:variable name="match" as="element()?">
                    <xsl:apply-templates select="$this" mode="find-match">
                        <xsl:with-param name="candidates" select="$control"/>
                    </xsl:apply-templates>
                </xsl:variable>

                <xsl:choose>
                    <xsl:when test="$match">
                        <xsl:apply-templates select="$this" mode="common">
                            <xsl:with-param name="control" select="$match"/>
                        </xsl:apply-templates>
                    </xsl:when>
                    <xsl:otherwise>
                        <xsl:apply-templates select="$this" mode="primary-only"/>
                    </xsl:otherwise>
                </xsl:choose>
                <xsl:call-template name="match-children">
                    <xsl:with-param name="primary" select="subsequence($primary, 2)"/>
                    <xsl:with-param name="control" select="if (not($match)) then $control else remove($control, 1 + count(set:leading($control, $match)))"/>
                </xsl:call-template>
            </xsl:when>
            <xsl:when test="$primary">
                <xsl:apply-templates select="$primary" mode="primary-only"/>
            </xsl:when>
            <xsl:when test="$control">
                <xsl:apply-templates select="$control" mode="control-only"/>
            </xsl:when>
        </xsl:choose>

    </xsl:template>

</xsl:stylesheet>

applied to this document (based on your test case), the result is PASS:
<test>
  <root>
    <tag name="AAA">
      <attr name="b" value="1"/>
      <attr name="c" value="2"/>
      <attr name="a" value="3"/>
    </tag>
    <tag name="BBB">
      <attr name="x" value="111"/>
      <attr name="z" value="222"/>
    </tag>
    <tag name="BBB">
      <attr name="x" value="333"/>
      <attr name="z" value="444"/>
    </tag>
  </root>
  <root>
    <tag name="AAA">
      <attr name="a" value="3"/>
      <attr name="b" value="1"/>
      <attr name="c" value="2"/>
    </tag>
    <tag name="BBB">
      <attr name="z" value="444"/>
      <attr name="x" value="333"/>
    </tag>
    <tag name="BBB">
      <attr name="x" value="111"/>
      <attr name="z" value="222"/>
    </tag>
  </root>
</test>

A: From your example, it looks like you only care about re-ordering  elements within  elements, but not reordering  elements themselves. If so, then (as a previous respondent said) you need to use sort, but on the  elements, not the  elements nor the attributes.
Many would find it confusing to have XML elements named "tag" and/or "attr", since those are terms with specific meanings already in XML -- possibly that contributed to trying to sort by "@*" instead of sorting  elements?
If your structure is really just like your example, a much more "XML-ish" representation would be:
<AAA b="1" c="2" a="3" />
<BBB x="111" z="222" />
<BBB x="333" z="444" />

Much more compact, avoids the terminology conflict, and makes the attributes be order-independent by definition -- which means any off-the-shelf XML diff utility will get the effect it seems you want, or you could just convert to canonical XML and use regular diff.


text:
Q: Crafting a custom call to inner_product (C++ STL) I'm having trouble getting my head around how to use inner_product to combine a std::vector<float> and a std::vector<std::vector<float>>. Given, e.g., <2,3> and <<4,5>,<6,7>>, I'd like inner_product to produce
2*<4,5> + 3*<6,7> = <8,10> + <18,21> = <26,31>.

Supposing
vector<float> foo;

and
vector<vector<float>> bar;

are initialized and are of equal size, I don't know what UK1, UK2, and UK3 in
vector<float> ip =
              inner_product(foo.begin(), foo.end(), bar.begin(), UK1, UK2, UK3);

should be. I suspect UK1 should be a vector filled with 0.0fs, of the same size as the vectors in bar. UK3 should perhaps be something like
std::transform(UK4.begin(), UK4.end(), UK4.begin(),
                                   std::bind1st(std::multiplies<float>(), UK5));

And I guess UK2 should somehow represent component-wise vector<float> addition!
I don't even want to think about how much more complex this will become when the vectors in bar are replaced by objects of a class with float attributes...

A: Define the add and multiply functions like this:
static vector<float> add(const vector<float> &a,const vector<float> &b)
{
  assert(a.size()==b.size());
  size_t n = a.size();
  vector<float> result(n);
  for (size_t i=0; i!=n; ++i) {
    result[i] = a[i]+b[i];
  }
  return result;
}

static vector<float> mul(const float &a,const vector<float> &b)
{
  size_t n = b.size();
  vector<float> result = b;
  for (size_t i=0; i!=n; ++i) {
    result[i] *= a;
  }
  return result;
}

And use it like this:
vector<float> zero(2,0);
vector<float> result =
  inner_product(a.begin(),a.end(),b.begin(),zero,add,mul);

A: std::inner_product accumulates a sum. UK2 is the sum operation. UK1 is normally the neutral element of UK2. UK3 is the multiplication operation that multiplies corresponding elements of the two sequences and returns a summand for UK2.
I guess std::valarray should provide a more suitable container for this operation.
// this is c++11
#include <vector>
#include <valarray>
#include <algorithm>
#include <iostream>

int main ()
{
    std::valarray <int> zero = { 0, 0 };
    std::vector <int> foo = { 1, 2, 3 };
    std::vector <std::valarray<int>> bar = { { 3, 4 }, { 5, 6 }, { 7, 8 } };
    std::valarray<int> result = std::inner_product (foo.begin(), foo.end(),
                                     bar.begin(), zero);
    for(auto n : result) {
        std::cout << n << ' ';
    }
    std::cout << std::endl;
}


text:
Q: Implementing Swipe action on ViewFlipper with multiple GridViews I have the following code to listen to Swipe action to navigate between GridViews in my ViewFlipper. However, it detects the Swipe inconsistently. I added the Gesture Listener to every GridView and also on every item in the GridView. Is there anything else I'm missing?
Full code is below:
public class ListNewsActivity extends Activity implements OnGestureListener {

String TAG = "ListNewsActivity";

private static final int SWIPE_MIN_DISTANCE = 120;
private static final int SWIPE_MAX_OFF_PATH = 250;
private static final int SWIPE_THRESHOLD_VELOCITY = 200;

private static final int DIALOG_PLEASE_WAIT = 100;
private GestureDetector gestureDetector;
View.OnTouchListener gestureListener;

private Animation slideLeftIn;
private Animation slideLeftOut;
private Animation slideRightIn;
private Animation slideRightOut;

private static int MAX_STREAMS = AppSettings.getStreamList().size();

Context context;

ViewFlipper flipper;

StreamHeader header;

int currentStreamIndex = 0;

ArrayList<StreamNav> navList = new ArrayList<StreamNav>();
ArrayList<StreamGridView> gridList = new ArrayList<StreamGridView>();

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {

    context = getApplicationContext();
    super.onCreate(savedInstanceState);
    setContentView(R.layout.stream);

    if (AppSettings.userToken == null) {
        AppSettings.getUserToken(context);
    }

    header = (StreamHeader) findViewById(R.id.stream_header);
    setHeaderTitle();

    flipper = (ViewFlipper)findViewById(R.id.stream_flipper);

    boolean loadData = false;
    Log.v(TAG, "No. of streams: " + String.valueOf(AppSettings.getStreamList().size()));
    for (Stream stream : AppSettings.getStreamList()) {
        Log.v(TAG, "Checking Stream  " + stream.getName());
        if (stream.getPosts() == null || stream.getPosts().size() == 0) {
            loadData = true;
            Log.v(TAG, "Empty Stream for " + stream.getBlogId() + ". Data will be loaded.");
            break;
        }
        else {
            Log.v(TAG, "Stream " + stream.getName() + " is populated. Posts: " + String.valueOf(stream.getPosts().size()));
        }
    }

    setupNavAndGrids();

    if (loadData) {
        new LoadStreamTask().execute();
    }
    else {
        populateGrids();
    }

    slideLeftIn = AnimationUtils.loadAnimation(this, R.anim.stream_flipper_slidein_from_right);
    slideLeftOut = AnimationUtils.loadAnimation(this, R.anim.stream_flipper_slideout_to_left);
    slideRightIn = AnimationUtils.loadAnimation(this, R.anim.stream_flipper_slidein_from_left);
    slideRightOut = AnimationUtils.loadAnimation(this, R.anim.stream_flipper_slideout_to_right);

    gestureDetector = new GestureDetector(new MyGestureDetector());
    gestureListener = new View.OnTouchListener() {
        public boolean onTouch(View v, MotionEvent event) {

            if (gestureDetector.onTouchEvent(event)) {
                return true;
            }
            return false;
        }
    };

}

public void setupNavAndGrids() {

    LinearLayout llNav = (LinearLayout) findViewById(R.id.stream_nav_layout);

    View.OnClickListener navOnClickListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            StreamNav nav = (StreamNav)v;
            navigateToStream(nav.getStreamIndex());

        }
    };

    for (int i = 0; i < MAX_STREAMS; i++) {
        StreamNav nav = new StreamNav(context, null);
        nav.setStreamIndex(i);
        nav.setOnClickListener(navOnClickListener);
        navList.add(nav);
        llNav.addView(nav);

        StreamGridView gv = new StreamGridView(context, null);
        gv.setOnTouchListener(gestureListener);
        gridList.add(gv);

        flipper.addView(gv);

    }

    navList.get(0).setSelected(true);

}

void navigateToStream(int newStreamIndex) {

    for (StreamNav nav : navList) {
        if (nav.getStreamIndex() == newStreamIndex) {
            nav.setSelected(true);
        }
        else {
            nav.setSelected(false);
        }
    }
    Log.v(TAG, "Navigate To Stream: currentStreamIndex=" + String.valueOf(currentStreamIndex) + " newStreamIndex " + String.valueOf(newStreamIndex));
    if (currentStreamIndex < newStreamIndex) {
        int ctr = newStreamIndex - currentStreamIndex;
        for (int i = 0; i < ctr; i++) {
            showNext();
        }
    }
    else {
        int ctr =  currentStreamIndex - newStreamIndex;
        for (int i = 0; i < ctr; i++) {
            showPrevious();
        }
    }
}

public void showNext() {
    Toast.makeText(context, "Show Next Page for Flipper", Toast.LENGTH_LONG);
    flipper.setInAnimation(this, R.anim.stream_flipper_slidein_from_right);
    flipper.setOutAnimation(this, R.anim.stream_flipper_slideout_to_left);
    flipper.showNext();
    setStreamIndex(1);
    setHeaderTitle();
    }

public void showPrevious() {
    Toast.makeText(context, "Show Previous Page for Flipper", Toast.LENGTH_LONG);
    flipper.setInAnimation(this, R.anim.stream_flipper_slidein_from_left);
    flipper.setOutAnimation(this, R.anim.stream_flipper_slideout_to_right);
    flipper.showPrevious();
    setStreamIndex(-1);
    setHeaderTitle();
}

void setStreamIndex(int step) {
    if (step == 1) {
        if (currentStreamIndex == MAX_STREAMS) {
            currentStreamIndex = 0;
        }
        else {
            currentStreamIndex++;
        }
    }
    else {
        // -1 which means previous
        if (currentStreamIndex == 0) {
            currentStreamIndex = MAX_STREAMS - 1;
        }
        else {
            currentStreamIndex--;
        }
    }
}

void setHeaderTitle() {
    header.setTitle(AppSettings.getStreamList().get(currentStreamIndex).getName());
}

void populateGrids() {
    int pos = -1;
    for (StreamGridView sgv : gridList) {
        pos++;
        Log.v(TAG, "Loading Stream for " + AppSettings.getStreamList().get(pos).getName() + "; Posts: " + String.valueOf(AppSettings.getStreamList().get(pos).getPosts().size()));
        ArrayList<Post> posts = AppSettings.getStreamList().get(pos).getPosts();
        sgv.adapter = new LazyPostItemAdapter(ListNewsActivity.this, posts, gestureListener);
        sgv.gvStream.setAdapter(sgv.adapter);

    }
}
class LoadStreamTask extends AsyncTask<Void, String, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        showDialog(DIALOG_PLEASE_WAIT);

    }

    @Override
    protected Void doInBackground(Void... unused) {

        for (Stream stream : AppSettings.getStreamList()) {

            if (stream.getBlogId().equalsIgnoreCase("popular")) {
                stream.setPosts(Post.getPopularStream());
            }
            else if (stream.getBlogId().equalsIgnoreCase("recent")) {
                stream.setPosts(Post.getRecentStream());
            }
            else {
                Blog blog = Blog.getBlog(stream.getBlogId());
                stream.setPosts(Post.getPostsForBlog(blog));
            }
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void unused) {

        populateGrids();
        dismissDialog(DIALOG_PLEASE_WAIT);
    }
}

@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
        case DIALOG_PLEASE_WAIT:
            ProgressDialog mProgressDialog;
            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setMessage("Loading Streams...");
            mProgressDialog.setCancelable(false);
            mProgressDialog.show();
            return mProgressDialog;
        default:
            return null;
    }
}

class MyGestureDetector extends SimpleOnGestureListener {
    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        Log.v(TAG, "onFling");
        try {
            if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
                return false;
            // right to left swipe
            if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                flipper.setInAnimation(slideLeftIn);
                flipper.setOutAnimation(slideLeftOut);
                flipper.showNext();
            }  else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                flipper.setInAnimation(slideRightIn);
                flipper.setOutAnimation(slideRightOut);
                flipper.showPrevious();
            }
        } catch (Exception e) {
            // nothing
        }
        return false;
    }
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    if (gestureDetector.onTouchEvent(event))
        return true;
    else
        return false;
}

@Override
public boolean onDown(MotionEvent e) {
    // TODO Auto-generated method stub
    return false;
}

@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
        float velocityY) {
    // TODO Auto-generated method stub
    return false;
}

@Override
public void onLongPress(MotionEvent e) {
    // TODO Auto-generated method stub

}

@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
        float distanceY) {
    // TODO Auto-generated method stub
    return false;
}

@Override
public void onShowPress(MotionEvent e) {
    // TODO Auto-generated method stub

}

@Override
public boolean onSingleTapUp(MotionEvent e) {
    // TODO Auto-generated method stub
    return false;
}

}

A: I keep seeing the same swipe gesture detection code all over StackOverflow, so I have attempted to clean it up a bit. This is a generic listener which can fire events for right or left swipes (easily extended to other
public class SwipeListener extends GestureDetector.SimpleOnGestureListener {

    private static final int SWIPE_MIN_DISTANCE = 120;
    private static final int SWIPE_MAX_OFF_PATH = 250;
    private static final int SWIPE_THRESHOLD_VELOCITY = 200;

    private SwipeHandler handler;

    public SwipeHandler getHandler() {
        return handler;
    }

    public void setHandler(SwipeHandler handler) {
        this.handler = handler;
    }

    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {

        if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
            return false;

        // left
        if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE
                && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {

            if (handler != null) {
                handler.onLeft();

                return true;
            }

        // right
        } else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
                && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {

            if (handler != null) {
                handler.onRight();

                return true;
            }
        }

        return super.onFling(e1, e2, velocityX, velocityY);
    }

    public static abstract class SwipeHandler{
        public void onLeft() {}
        public void onRight() {}
    }
}

And then to use this anywhere, just create an instance, setup your swipe event handlers, and attach it:
    SwipeListener swipeListener = new SwipeListener();
    swipeListener.setHandler(new SwipeListener.SwipeHandler() {
        @Override
        public void onRight() {
            doSomething();
        }
    });

    someView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            return gestureDetector.onTouchEvent(event);
        }
    });

A: I have a couple of questions/observations here:
Q: Can you elaborate on what you mean by inconsistently? Is there any pattern to when the swipe is not    detected? Does it work at all? If so, when?
Q: In your main Activity, in the over-riden onTouchEvent(MotionEvent me) method do you return    myGestureDetector.onTouchEvent(me) like this?
@Override
public boolean onTouchEvent(MotionEvent me) {
     return myGestureDetector.onTouchEvent(me);
}

here myGestureDetector is an object of your MyGestureDetector class and this basically attaches your GestureDetector to the touch event
Observation: Can you please return true as soon as your gesture processing is done, that tells android that the gesture capture is done, for example
        if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
            flipper.setInAnimation(slideLeftIn);
            flipper.setOutAnimation(slideLeftOut);
            flipper.showNext();
            //return true if the gesture event is consumed
            return true;
        }  else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
            flipper.setInAnimation(slideRightIn);
            flipper.setOutAnimation(slideRightOut);
            flipper.showPrevious();
            //return true if the gesture event is consumed
            return true;
        }

A: 1) have u added all the gridviews in viewflipper.
viewFlipper = (ViewFlipper)findViewById(R.id.flipper);
            slideLeftIn = AnimationUtils.loadAnimation(this, R.anim.slide_left_in);
            slideLeftOut = AnimationUtils.loadAnimation(this, R.anim.slide_left_out);
            slideRightIn = AnimationUtils.loadAnimation(this, R.anim.slide_right_in);
            slideRightOut = AnimationUtils.loadAnimation(this, R.anim.slide_right_out);

            gestureDetector = new GestureDetector(new MyGestureDetector());
            gestureListener = new View.OnTouchListener()
                {
                    public boolean onTouch(View v, MotionEvent event)
                    {
                        if (gestureDetector.onTouchEvent(event))
                        {
                                return true;
                        }
                        else{
                                return false;}
                        }
                };

I have added these in my code it is working fine.just check this let me know


text:
Q: parindent with KOMAscript I have decided to use KOMA for my new project. I'm writing in Spanish so I have to indent every first paragraph line, but I also want to include a paragraph separation of 1/2 line.
If I set KOMAoption to parksip=false I get the indentation but not the space between paragraphs. If I set parskip=half, the otherway around.
The only option I found is setting parskip=half and after begin{document} include \setlength{\parindent}{1em}. But then, I don't know if someother spacing settings in KOMA will be changed.
Is there any option I haven't found in KOMA that makes it possible to do it in a more elegant way.
Any comment is more than welcome.


text:
Q: How to put spool mode off in tpt export? I am trying to switch off spool mode in tpt export. Unfortunately I am not able to identify the option to do so. I am new to teradata. Can anyone please help.
I saw one option in the internet , Spoolmode NOSPOOL. But not sure how to use it in the tpt export script.

A: If by spool you mean not spooling the data and output you can try bteq:
bteq << EOF >/dev/null
.sessions 16
.logon $TDSRV/$TDUSER,$TDPASSWD

.EXPORT FILE = $OUTPUT_DIR/$OUTPUT_FILE;
.SET WIDTH 12000
.SET TITLEDASHES OFF

SELECT * FROM TABLE;

.LOGOFF
.EXIT
EOF

A: you do this
VARCHAR SpoolMode      = 'NOSPOOL'


text:
Q: not able to see In app purchase test user on Clicking of Manage user i want to set up a test account to test in app purchase on sandbox,  i am logging into intunes connect and following the same procedure as prescribed in the itunes connect developer guide. i am clinking on manage user, but i am not able to see the window where i can select test in app purchase user.
do i need to do any change in my profile to make it visible.

A: Just didn't had the paid app contract certificate so wasn't getting the page
now it is working fine... In case anybody is stuck in this, check it once.